blob: fb108885e4ce74984c9d0e577962b72bbb25cb3d [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Barry Warsaw04f357c2002-07-23 19:04:11 +00005from test import test_support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Tim Petersa7def722004-08-23 22:13:22 +00007import warnings
Tim Peters8485b562004-08-04 18:46:34 +00008
Nick Coghlana2053472008-12-14 10:54:50 +00009# NOTE: There are some additional tests relating to interaction with
10# zipimport in the test_zipimport_support test module.
11
Tim Peters8485b562004-08-04 18:46:34 +000012######################################################################
13## Sample Objects (used by test cases)
14######################################################################
15
16def sample_func(v):
17 """
Tim Peters19397e52004-08-06 22:02:59 +000018 Blah blah
19
Tim Peters8485b562004-08-04 18:46:34 +000020 >>> print sample_func(22)
21 44
Tim Peters19397e52004-08-06 22:02:59 +000022
23 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000024 """
25 return v+v
26
27class SampleClass:
28 """
29 >>> print 1
30 1
Edward Loper4ae900f2004-09-21 03:20:34 +000031
32 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
33 >>>
34 ...
35
36 Multiline example:
37 >>> sc = SampleClass(3)
38 >>> for i in range(10):
39 ... sc = sc.double()
40 ... print sc.get(),
41 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000042 """
43 def __init__(self, val):
44 """
45 >>> print SampleClass(12).get()
46 12
47 """
48 self.val = val
49
50 def double(self):
51 """
52 >>> print SampleClass(12).double().get()
53 24
54 """
55 return SampleClass(self.val + self.val)
56
57 def get(self):
58 """
59 >>> print SampleClass(-5).get()
60 -5
61 """
62 return self.val
63
64 def a_staticmethod(v):
65 """
66 >>> print SampleClass.a_staticmethod(10)
67 11
68 """
69 return v+1
70 a_staticmethod = staticmethod(a_staticmethod)
71
72 def a_classmethod(cls, v):
73 """
74 >>> print SampleClass.a_classmethod(10)
75 12
76 >>> print SampleClass(0).a_classmethod(10)
77 12
78 """
79 return v+2
80 a_classmethod = classmethod(a_classmethod)
81
82 a_property = property(get, doc="""
83 >>> print SampleClass(22).a_property
84 22
85 """)
86
87 class NestedClass:
88 """
89 >>> x = SampleClass.NestedClass(5)
90 >>> y = x.square()
91 >>> print y.get()
92 25
93 """
94 def __init__(self, val=0):
95 """
96 >>> print SampleClass.NestedClass().get()
97 0
98 """
99 self.val = val
100 def square(self):
101 return SampleClass.NestedClass(self.val*self.val)
102 def get(self):
103 return self.val
104
105class SampleNewStyleClass(object):
106 r"""
107 >>> print '1\n2\n3'
108 1
109 2
110 3
111 """
112 def __init__(self, val):
113 """
114 >>> print SampleNewStyleClass(12).get()
115 12
116 """
117 self.val = val
118
119 def double(self):
120 """
121 >>> print SampleNewStyleClass(12).double().get()
122 24
123 """
124 return SampleNewStyleClass(self.val + self.val)
125
126 def get(self):
127 """
128 >>> print SampleNewStyleClass(-5).get()
129 -5
130 """
131 return self.val
132
133######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000134## Fake stdin (for testing interactive debugging)
135######################################################################
136
137class _FakeInput:
138 """
139 A fake input stream for pdb's interactive debugger. Whenever a
140 line is read, print it (to simulate the user typing it), and then
141 return it. The set of lines to return is specified in the
142 constructor; they should not have trailing newlines.
143 """
144 def __init__(self, lines):
145 self.lines = lines
146
147 def readline(self):
148 line = self.lines.pop(0)
149 print line
150 return line+'\n'
151
152######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000153## Test Cases
154######################################################################
155
156def test_Example(): r"""
157Unit tests for the `Example` class.
158
Edward Lopera6b68322004-08-26 00:05:43 +0000159Example is a simple container class that holds:
160 - `source`: A source string.
161 - `want`: An expected output string.
162 - `exc_msg`: An expected exception message string (or None if no
163 exception is expected).
164 - `lineno`: A line number (within the docstring).
165 - `indent`: The example's indentation in the input string.
166 - `options`: An option dictionary, mapping option flags to True or
167 False.
Tim Peters8485b562004-08-04 18:46:34 +0000168
Edward Lopera6b68322004-08-26 00:05:43 +0000169These attributes are set by the constructor. `source` and `want` are
170required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000171
Edward Lopera6b68322004-08-26 00:05:43 +0000172 >>> example = doctest.Example('print 1', '1\n')
173 >>> (example.source, example.want, example.exc_msg,
174 ... example.lineno, example.indent, example.options)
175 ('print 1\n', '1\n', None, 0, 0, {})
176
177The first three attributes (`source`, `want`, and `exc_msg`) may be
178specified positionally; the remaining arguments should be specified as
179keyword arguments:
180
181 >>> exc_msg = 'IndexError: pop from an empty list'
182 >>> example = doctest.Example('[].pop()', '', exc_msg,
183 ... lineno=5, indent=4,
184 ... options={doctest.ELLIPSIS: True})
185 >>> (example.source, example.want, example.exc_msg,
186 ... example.lineno, example.indent, example.options)
187 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
188
189The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000190
Tim Petersbb431472004-08-09 03:51:46 +0000191 Source spans a single line: no terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000192 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000193 >>> e.source, e.want
194 ('print 1\n', '1\n')
195
Edward Lopera6b68322004-08-26 00:05:43 +0000196 >>> e = doctest.Example('print 1\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000197 >>> e.source, e.want
198 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000199
Tim Petersbb431472004-08-09 03:51:46 +0000200 Source spans multiple lines: require terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000201 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000202 >>> e.source, e.want
203 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000204
Edward Lopera6b68322004-08-26 00:05:43 +0000205 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000206 >>> e.source, e.want
207 ('print 1;\nprint 2\n', '1\n2\n')
208
Edward Lopera6b68322004-08-26 00:05:43 +0000209 Empty source string (which should never appear in real examples)
210 >>> e = doctest.Example('', '')
211 >>> e.source, e.want
212 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000213
Edward Lopera6b68322004-08-26 00:05:43 +0000214The constructor normalizes the `want` string to end in a newline,
215unless it's the empty string:
216
217 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000218 >>> e.source, e.want
219 ('print 1\n', '1\n')
220
Edward Lopera6b68322004-08-26 00:05:43 +0000221 >>> e = doctest.Example('print 1', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000222 >>> e.source, e.want
223 ('print 1\n', '1\n')
224
Edward Lopera6b68322004-08-26 00:05:43 +0000225 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000226 >>> e.source, e.want
227 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000228
229The constructor normalizes the `exc_msg` string to end in a newline,
230unless it's `None`:
231
232 Message spans one line
233 >>> exc_msg = 'IndexError: pop from an empty list'
234 >>> e = doctest.Example('[].pop()', '', exc_msg)
235 >>> e.exc_msg
236 'IndexError: pop from an empty list\n'
237
238 >>> exc_msg = 'IndexError: pop from an empty list\n'
239 >>> e = doctest.Example('[].pop()', '', exc_msg)
240 >>> e.exc_msg
241 'IndexError: pop from an empty list\n'
242
243 Message spans multiple lines
244 >>> exc_msg = 'ValueError: 1\n 2'
245 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
246 >>> e.exc_msg
247 'ValueError: 1\n 2\n'
248
249 >>> exc_msg = 'ValueError: 1\n 2\n'
250 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
251 >>> e.exc_msg
252 'ValueError: 1\n 2\n'
253
254 Empty (but non-None) exception message (which should never appear
255 in real examples)
256 >>> exc_msg = ''
257 >>> e = doctest.Example('raise X()', '', exc_msg)
258 >>> e.exc_msg
259 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000260"""
261
262def test_DocTest(): r"""
263Unit tests for the `DocTest` class.
264
265DocTest is a collection of examples, extracted from a docstring, along
266with information about where the docstring comes from (a name,
267filename, and line number). The docstring is parsed by the `DocTest`
268constructor:
269
270 >>> docstring = '''
271 ... >>> print 12
272 ... 12
273 ...
274 ... Non-example text.
275 ...
276 ... >>> print 'another\example'
277 ... another
278 ... example
279 ... '''
280 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000281 >>> parser = doctest.DocTestParser()
282 >>> test = parser.get_doctest(docstring, globs, 'some_test',
283 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000284 >>> print test
285 <DocTest some_test from some_file:20 (2 examples)>
286 >>> len(test.examples)
287 2
288 >>> e1, e2 = test.examples
289 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000290 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000291 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000292 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000293
294Source information (name, filename, and line number) is available as
295attributes on the doctest object:
296
297 >>> (test.name, test.filename, test.lineno)
298 ('some_test', 'some_file', 20)
299
300The line number of an example within its containing file is found by
301adding the line number of the example and the line number of its
302containing test:
303
304 >>> test.lineno + e1.lineno
305 21
306 >>> test.lineno + e2.lineno
307 26
308
309If the docstring contains inconsistant leading whitespace in the
310expected output of an example, then `DocTest` will raise a ValueError:
311
312 >>> docstring = r'''
313 ... >>> print 'bad\nindentation'
314 ... bad
315 ... indentation
316 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000317 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000318 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000319 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000320
321If the docstring contains inconsistent leading whitespace on
322continuation lines, then `DocTest` will raise a ValueError:
323
324 >>> docstring = r'''
325 ... >>> print ('bad indentation',
326 ... ... 2)
327 ... ('bad', 'indentation')
328 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000329 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000330 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000331 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
Tim Peters8485b562004-08-04 18:46:34 +0000332
333If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
334will raise a ValueError:
335
336 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000337 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000338 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000339 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
340
341If there's no blank space after a PS2 prompt ('...'), then `DocTest`
342will raise a ValueError:
343
344 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000345 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000346 Traceback (most recent call last):
347 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
348
Tim Peters8485b562004-08-04 18:46:34 +0000349"""
350
Tim Peters8485b562004-08-04 18:46:34 +0000351def test_DocTestFinder(): r"""
352Unit tests for the `DocTestFinder` class.
353
354DocTestFinder is used to extract DocTests from an object's docstring
355and the docstrings of its contained objects. It can be used with
356modules, functions, classes, methods, staticmethods, classmethods, and
357properties.
358
359Finding Tests in Functions
360~~~~~~~~~~~~~~~~~~~~~~~~~~
361For a function whose docstring contains examples, DocTestFinder.find()
362will return a single test (for that function's docstring):
363
Tim Peters8485b562004-08-04 18:46:34 +0000364 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000365
366We'll simulate a __file__ attr that ends in pyc:
367
368 >>> import test.test_doctest
369 >>> old = test.test_doctest.__file__
370 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
371
Tim Peters8485b562004-08-04 18:46:34 +0000372 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000373
Edward Loper74bca7a2004-08-12 02:27:44 +0000374 >>> print tests # doctest: +ELLIPSIS
Nick Coghlana2053472008-12-14 10:54:50 +0000375 [<DocTest sample_func from ...:16 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000376
Tim Peters4de7c5c2004-08-23 22:38:05 +0000377The exact name depends on how test_doctest was invoked, so allow for
378leading path components.
379
380 >>> tests[0].filename # doctest: +ELLIPSIS
381 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000382
383 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000384
Jim Fulton07a349c2004-08-22 14:10:00 +0000385
Tim Peters8485b562004-08-04 18:46:34 +0000386 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000387 >>> (e.source, e.want, e.lineno)
388 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000389
Edward Loper32ddbf72004-09-13 05:47:24 +0000390By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000391
392 >>> def no_docstring(v):
393 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000394 >>> finder.find(no_docstring)
395 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000396
397However, the optional argument `exclude_empty` to the DocTestFinder
398constructor can be used to exclude tests for objects with empty
399docstrings:
400
401 >>> def no_docstring(v):
402 ... pass
403 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
404 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000405 []
406
407If the function has a docstring with no examples, then a test with no
408examples is returned. (This lets `DocTestRunner` collect statistics
409about which functions have no tests -- but is that useful? And should
410an empty test also be created when there's no docstring?)
411
412 >>> def no_examples(v):
413 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000414 >>> finder.find(no_examples) # doctest: +ELLIPSIS
415 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000416
417Finding Tests in Classes
418~~~~~~~~~~~~~~~~~~~~~~~~
419For a class, DocTestFinder will create a test for the class's
420docstring, and will recursively explore its contents, including
421methods, classmethods, staticmethods, properties, and nested classes.
422
423 >>> finder = doctest.DocTestFinder()
424 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000425 >>> for t in tests:
426 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000427 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000428 3 SampleClass.NestedClass
429 1 SampleClass.NestedClass.__init__
430 1 SampleClass.__init__
431 2 SampleClass.a_classmethod
432 1 SampleClass.a_property
433 1 SampleClass.a_staticmethod
434 1 SampleClass.double
435 1 SampleClass.get
436
437New-style classes are also supported:
438
439 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000440 >>> for t in tests:
441 ... print '%2s %s' % (len(t.examples), t.name)
442 1 SampleNewStyleClass
443 1 SampleNewStyleClass.__init__
444 1 SampleNewStyleClass.double
445 1 SampleNewStyleClass.get
446
447Finding Tests in Modules
448~~~~~~~~~~~~~~~~~~~~~~~~
449For a module, DocTestFinder will create a test for the class's
450docstring, and will recursively explore its contents, including
451functions, classes, and the `__test__` dictionary, if it exists:
452
453 >>> # A module
Christian Heimesc756d002007-11-27 21:34:01 +0000454 >>> import types
455 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000456 >>> def triple(val):
457 ... '''
Edward Loper4ae900f2004-09-21 03:20:34 +0000458 ... >>> print triple(11)
Tim Peters8485b562004-08-04 18:46:34 +0000459 ... 33
460 ... '''
461 ... return val*3
462 >>> m.__dict__.update({
463 ... 'sample_func': sample_func,
464 ... 'SampleClass': SampleClass,
465 ... '__doc__': '''
466 ... Module docstring.
467 ... >>> print 'module'
468 ... module
469 ... ''',
470 ... '__test__': {
471 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
472 ... 'c': triple}})
473
474 >>> finder = doctest.DocTestFinder()
475 >>> # Use module=test.test_doctest, to prevent doctest from
476 >>> # ignoring the objects since they weren't defined in m.
477 >>> import test.test_doctest
478 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000479 >>> for t in tests:
480 ... print '%2s %s' % (len(t.examples), t.name)
481 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000482 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000483 3 some_module.SampleClass.NestedClass
484 1 some_module.SampleClass.NestedClass.__init__
485 1 some_module.SampleClass.__init__
486 2 some_module.SampleClass.a_classmethod
487 1 some_module.SampleClass.a_property
488 1 some_module.SampleClass.a_staticmethod
489 1 some_module.SampleClass.double
490 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000491 1 some_module.__test__.c
492 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000493 1 some_module.sample_func
494
495Duplicate Removal
496~~~~~~~~~~~~~~~~~
497If a single object is listed twice (under different names), then tests
498will only be generated for it once:
499
Tim Petersf3f57472004-08-08 06:11:48 +0000500 >>> from test import doctest_aliases
Amaury Forgeot d'Arcf81ff982009-06-14 21:20:40 +0000501 >>> assert doctest_aliases.TwoNames.f
502 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000503 >>> tests = excl_empty_finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000504 >>> print len(tests)
505 2
506 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000507 test.doctest_aliases.TwoNames
508
509 TwoNames.f and TwoNames.g are bound to the same object.
510 We can't guess which will be found in doctest's traversal of
511 TwoNames.__dict__ first, so we have to allow for either.
512
513 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000514 True
515
Tim Petersbf0400a2006-06-05 01:43:03 +0000516Empty Tests
517~~~~~~~~~~~
518By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000519
Tim Petersbf0400a2006-06-05 01:43:03 +0000520 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000521 >>> for t in tests:
522 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000523 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000524 3 SampleClass.NestedClass
525 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000526 1 SampleClass.__init__
Tim Petersbf0400a2006-06-05 01:43:03 +0000527 2 SampleClass.a_classmethod
528 1 SampleClass.a_property
529 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000530 1 SampleClass.double
531 1 SampleClass.get
532
533By default, that excluded objects with no doctests. exclude_empty=False
534tells it to include (empty) tests for objects with no doctests. This feature
535is really to support backward compatibility in what doctest.master.summarize()
536displays.
537
Tim Petersbf0400a2006-06-05 01:43:03 +0000538 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000539 >>> for t in tests:
540 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000541 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000542 3 SampleClass.NestedClass
543 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000544 0 SampleClass.NestedClass.get
545 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000546 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000547 2 SampleClass.a_classmethod
548 1 SampleClass.a_property
549 1 SampleClass.a_staticmethod
550 1 SampleClass.double
551 1 SampleClass.get
552
Tim Peters8485b562004-08-04 18:46:34 +0000553Turning off Recursion
554~~~~~~~~~~~~~~~~~~~~~
555DocTestFinder can be told not to look for tests in contained objects
556using the `recurse` flag:
557
558 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000559 >>> for t in tests:
560 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000561 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000562
563Line numbers
564~~~~~~~~~~~~
565DocTestFinder finds the line number of each example:
566
567 >>> def f(x):
568 ... '''
569 ... >>> x = 12
570 ...
571 ... some text
572 ...
573 ... >>> # examples are not created for comments & bare prompts.
574 ... >>>
575 ... ...
576 ...
577 ... >>> for x in range(10):
578 ... ... print x,
579 ... 0 1 2 3 4 5 6 7 8 9
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000580 ... >>> x//2
Edward Loperb51b2342004-08-17 16:37:12 +0000581 ... 6
582 ... '''
583 >>> test = doctest.DocTestFinder().find(f)[0]
584 >>> [e.lineno for e in test.examples]
585 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000586"""
587
Edward Loper00f8da72004-08-26 18:05:07 +0000588def test_DocTestParser(): r"""
589Unit tests for the `DocTestParser` class.
590
591DocTestParser is used to parse docstrings containing doctest examples.
592
593The `parse` method divides a docstring into examples and intervening
594text:
595
596 >>> s = '''
597 ... >>> x, y = 2, 3 # no output expected
598 ... >>> if 1:
599 ... ... print x
600 ... ... print y
601 ... 2
602 ... 3
603 ...
604 ... Some text.
605 ... >>> x+y
606 ... 5
607 ... '''
608 >>> parser = doctest.DocTestParser()
609 >>> for piece in parser.parse(s):
610 ... if isinstance(piece, doctest.Example):
611 ... print 'Example:', (piece.source, piece.want, piece.lineno)
612 ... else:
613 ... print ' Text:', `piece`
614 Text: '\n'
615 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
616 Text: ''
617 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
618 Text: '\nSome text.\n'
619 Example: ('x+y\n', '5\n', 9)
620 Text: ''
621
622The `get_examples` method returns just the examples:
623
624 >>> for piece in parser.get_examples(s):
625 ... print (piece.source, piece.want, piece.lineno)
626 ('x, y = 2, 3 # no output expected\n', '', 1)
627 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
628 ('x+y\n', '5\n', 9)
629
630The `get_doctest` method creates a Test from the examples, along with the
631given arguments:
632
633 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
634 >>> (test.name, test.filename, test.lineno)
635 ('name', 'filename', 5)
636 >>> for piece in test.examples:
637 ... print (piece.source, piece.want, piece.lineno)
638 ('x, y = 2, 3 # no output expected\n', '', 1)
639 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
640 ('x+y\n', '5\n', 9)
641"""
642
Tim Peters8485b562004-08-04 18:46:34 +0000643class test_DocTestRunner:
644 def basics(): r"""
645Unit tests for the `DocTestRunner` class.
646
647DocTestRunner is used to run DocTest test cases, and to accumulate
648statistics. Here's a simple DocTest case we can use:
649
650 >>> def f(x):
651 ... '''
652 ... >>> x = 12
653 ... >>> print x
654 ... 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000655 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000656 ... 6
657 ... '''
658 >>> test = doctest.DocTestFinder().find(f)[0]
659
660The main DocTestRunner interface is the `run` method, which runs a
661given DocTest case in a given namespace (globs). It returns a tuple
662`(f,t)`, where `f` is the number of failed tests and `t` is the number
663of tried tests.
664
665 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000666 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000667
668If any example produces incorrect output, then the test runner reports
669the failure and proceeds to the next example:
670
671 >>> def f(x):
672 ... '''
673 ... >>> x = 12
674 ... >>> print x
675 ... 14
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000676 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000677 ... 6
678 ... '''
679 >>> test = doctest.DocTestFinder().find(f)[0]
680 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000681 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000682 Trying:
683 x = 12
684 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000685 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000686 Trying:
687 print x
688 Expecting:
689 14
Tim Peters8485b562004-08-04 18:46:34 +0000690 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000691 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000692 Failed example:
693 print x
694 Expected:
695 14
696 Got:
697 12
Edward Loperaacf0832004-08-26 01:19:50 +0000698 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000699 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000700 Expecting:
701 6
Tim Peters8485b562004-08-04 18:46:34 +0000702 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000703 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000704"""
705 def verbose_flag(): r"""
706The `verbose` flag makes the test runner generate more detailed
707output:
708
709 >>> def f(x):
710 ... '''
711 ... >>> x = 12
712 ... >>> print x
713 ... 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000714 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000715 ... 6
716 ... '''
717 >>> test = doctest.DocTestFinder().find(f)[0]
718
719 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000720 Trying:
721 x = 12
722 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000723 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000724 Trying:
725 print x
726 Expecting:
727 12
Tim Peters8485b562004-08-04 18:46:34 +0000728 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000729 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000730 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000731 Expecting:
732 6
Tim Peters8485b562004-08-04 18:46:34 +0000733 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000734 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000735
736If the `verbose` flag is unspecified, then the output will be verbose
737iff `-v` appears in sys.argv:
738
739 >>> # Save the real sys.argv list.
740 >>> old_argv = sys.argv
741
742 >>> # If -v does not appear in sys.argv, then output isn't verbose.
743 >>> sys.argv = ['test']
744 >>> doctest.DocTestRunner().run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000745 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000746
747 >>> # If -v does appear in sys.argv, then output is verbose.
748 >>> sys.argv = ['test', '-v']
749 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000750 Trying:
751 x = 12
752 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000753 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000754 Trying:
755 print x
756 Expecting:
757 12
Tim Peters8485b562004-08-04 18:46:34 +0000758 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000759 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000760 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000761 Expecting:
762 6
Tim Peters8485b562004-08-04 18:46:34 +0000763 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000764 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000765
766 >>> # Restore sys.argv
767 >>> sys.argv = old_argv
768
769In the remaining examples, the test runner's verbosity will be
770explicitly set, to ensure that the test behavior is consistent.
771 """
772 def exceptions(): r"""
773Tests of `DocTestRunner`'s exception handling.
774
775An expected exception is specified with a traceback message. The
776lines between the first line and the type/value may be omitted or
777replaced with any other string:
778
779 >>> def f(x):
780 ... '''
781 ... >>> x = 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000782 ... >>> print x//0
Tim Peters8485b562004-08-04 18:46:34 +0000783 ... Traceback (most recent call last):
784 ... ZeroDivisionError: integer division or modulo by zero
785 ... '''
786 >>> test = doctest.DocTestFinder().find(f)[0]
787 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000788 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000789
Edward Loper19b19582004-08-25 23:07:03 +0000790An example may not generate output before it raises an exception; if
791it does, then the traceback message will not be recognized as
792signaling an expected exception, so the example will be reported as an
793unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000794
795 >>> def f(x):
796 ... '''
797 ... >>> x = 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000798 ... >>> print 'pre-exception output', x//0
Tim Peters8485b562004-08-04 18:46:34 +0000799 ... pre-exception output
800 ... Traceback (most recent call last):
801 ... ZeroDivisionError: integer division or modulo by zero
802 ... '''
803 >>> test = doctest.DocTestFinder().find(f)[0]
804 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000805 ... # doctest: +ELLIPSIS
806 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000807 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000808 Failed example:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000809 print 'pre-exception output', x//0
Edward Loper19b19582004-08-25 23:07:03 +0000810 Exception raised:
811 ...
812 ZeroDivisionError: integer division or modulo by zero
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000813 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000814
815Exception messages may contain newlines:
816
817 >>> def f(x):
818 ... r'''
819 ... >>> raise ValueError, 'multi\nline\nmessage'
820 ... Traceback (most recent call last):
821 ... ValueError: multi
822 ... line
823 ... message
824 ... '''
825 >>> test = doctest.DocTestFinder().find(f)[0]
826 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000827 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000828
829If an exception is expected, but an exception with the wrong type or
830message is raised, then it is reported as a failure:
831
832 >>> def f(x):
833 ... r'''
834 ... >>> raise ValueError, 'message'
835 ... Traceback (most recent call last):
836 ... ValueError: wrong message
837 ... '''
838 >>> test = doctest.DocTestFinder().find(f)[0]
839 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000840 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000841 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000842 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000843 Failed example:
844 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000845 Expected:
846 Traceback (most recent call last):
847 ValueError: wrong message
848 Got:
849 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000850 ...
Tim Peters8485b562004-08-04 18:46:34 +0000851 ValueError: message
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000852 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000853
Tim Peters1fbf9c52004-09-04 17:21:02 +0000854However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
855detail:
856
857 >>> def f(x):
858 ... r'''
859 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
860 ... Traceback (most recent call last):
861 ... ValueError: wrong message
862 ... '''
863 >>> test = doctest.DocTestFinder().find(f)[0]
864 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000865 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000866
867But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
868
869 >>> def f(x):
870 ... r'''
871 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
872 ... Traceback (most recent call last):
873 ... TypeError: wrong type
874 ... '''
875 >>> test = doctest.DocTestFinder().find(f)[0]
876 >>> doctest.DocTestRunner(verbose=False).run(test)
877 ... # doctest: +ELLIPSIS
878 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000879 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000880 Failed example:
881 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
882 Expected:
883 Traceback (most recent call last):
884 TypeError: wrong type
885 Got:
886 Traceback (most recent call last):
887 ...
888 ValueError: message
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000889 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000890
Tim Peters8485b562004-08-04 18:46:34 +0000891If an exception is raised but not expected, then it is reported as an
892unexpected exception:
893
Tim Peters8485b562004-08-04 18:46:34 +0000894 >>> def f(x):
895 ... r'''
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000896 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000897 ... 0
898 ... '''
899 >>> test = doctest.DocTestFinder().find(f)[0]
900 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000901 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000902 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000903 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000904 Failed example:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000905 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000906 Exception raised:
907 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000908 ...
Tim Peters8485b562004-08-04 18:46:34 +0000909 ZeroDivisionError: integer division or modulo by zero
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000910 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000911"""
912 def optionflags(): r"""
913Tests of `DocTestRunner`'s option flag handling.
914
915Several option flags can be used to customize the behavior of the test
916runner. These are defined as module constants in doctest, and passed
Georg Brandlf725b952008-01-05 19:44:22 +0000917to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +0000918together).
919
920The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
921and 1/0:
922
923 >>> def f(x):
924 ... '>>> True\n1\n'
925
926 >>> # Without the flag:
927 >>> test = doctest.DocTestFinder().find(f)[0]
928 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000929 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000930
931 >>> # With the flag:
932 >>> test = doctest.DocTestFinder().find(f)[0]
933 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
934 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000935 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000936 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000937 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000938 Failed example:
939 True
940 Expected:
941 1
942 Got:
943 True
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000944 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000945
946The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
947and the '<BLANKLINE>' marker:
948
949 >>> def f(x):
950 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
951
952 >>> # Without the flag:
953 >>> test = doctest.DocTestFinder().find(f)[0]
954 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000955 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000956
957 >>> # With the flag:
958 >>> test = doctest.DocTestFinder().find(f)[0]
959 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
960 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000961 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000962 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000963 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000964 Failed example:
965 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000966 Expected:
967 a
968 <BLANKLINE>
969 b
970 Got:
971 a
972 <BLANKLINE>
973 b
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000974 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000975
976The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
977treated as equal:
978
979 >>> def f(x):
980 ... '>>> print 1, 2, 3\n 1 2\n 3'
981
982 >>> # Without the flag:
983 >>> test = doctest.DocTestFinder().find(f)[0]
984 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000985 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000986 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000987 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000988 Failed example:
989 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000990 Expected:
991 1 2
992 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000993 Got:
994 1 2 3
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000995 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000996
997 >>> # With the flag:
998 >>> test = doctest.DocTestFinder().find(f)[0]
999 >>> flags = doctest.NORMALIZE_WHITESPACE
1000 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001001 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001002
Tim Peters026f8dc2004-08-19 16:38:58 +00001003 An example from the docs:
1004 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
1005 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1006 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1007
Tim Peters8485b562004-08-04 18:46:34 +00001008The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1009output to match any substring in the actual output:
1010
1011 >>> def f(x):
1012 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1013
1014 >>> # Without the flag:
1015 >>> test = doctest.DocTestFinder().find(f)[0]
1016 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001017 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001018 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001019 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001020 Failed example:
1021 print range(15)
1022 Expected:
1023 [0, 1, 2, ..., 14]
1024 Got:
1025 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001026 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001027
1028 >>> # With the flag:
1029 >>> test = doctest.DocTestFinder().find(f)[0]
1030 >>> flags = doctest.ELLIPSIS
1031 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001032 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001033
Tim Peterse594bee2004-08-22 01:47:51 +00001034 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001035
1036 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001037 ... print i**2, #doctest: +ELLIPSIS
1038 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001039
Tim Peters026f8dc2004-08-19 16:38:58 +00001040 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001041
1042 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001043 ... print i,
1044 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001045
Tim Peters026f8dc2004-08-19 16:38:58 +00001046 Examples from the docs:
1047
1048 >>> print range(20) # doctest:+ELLIPSIS
1049 [0, 1, ..., 18, 19]
1050
1051 >>> print range(20) # doctest: +ELLIPSIS
1052 ... # doctest: +NORMALIZE_WHITESPACE
1053 [0, 1, ..., 18, 19]
1054
Tim Peters711bf302006-04-25 03:31:36 +00001055The SKIP flag causes an example to be skipped entirely. I.e., the
1056example is not run. It can be useful in contexts where doctest
1057examples serve as both documentation and test cases, and an example
1058should be included for documentation purposes, but should not be
1059checked (e.g., because its output is random, or depends on resources
1060which would be unavailable.) The SKIP flag can also be used for
1061'commenting out' broken examples.
1062
1063 >>> import unavailable_resource # doctest: +SKIP
1064 >>> unavailable_resource.do_something() # doctest: +SKIP
1065 >>> unavailable_resource.blow_up() # doctest: +SKIP
1066 Traceback (most recent call last):
1067 ...
1068 UncheckedBlowUpError: Nobody checks me.
1069
1070 >>> import random
1071 >>> print random.random() # doctest: +SKIP
1072 0.721216923889
1073
Edward Loper71f55af2004-08-26 01:41:51 +00001074The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001075and actual outputs to be displayed using a unified diff:
1076
1077 >>> def f(x):
1078 ... r'''
1079 ... >>> print '\n'.join('abcdefg')
1080 ... a
1081 ... B
1082 ... c
1083 ... d
1084 ... f
1085 ... g
1086 ... h
1087 ... '''
1088
1089 >>> # Without the flag:
1090 >>> test = doctest.DocTestFinder().find(f)[0]
1091 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001092 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001093 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001094 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001095 Failed example:
1096 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001097 Expected:
1098 a
1099 B
1100 c
1101 d
1102 f
1103 g
1104 h
1105 Got:
1106 a
1107 b
1108 c
1109 d
1110 e
1111 f
1112 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001113 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001114
1115 >>> # With the flag:
1116 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001117 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001118 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001119 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001120 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001121 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001122 Failed example:
1123 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001124 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001125 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001126 a
1127 -B
1128 +b
1129 c
1130 d
1131 +e
1132 f
1133 g
1134 -h
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001135 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001136
Edward Loper71f55af2004-08-26 01:41:51 +00001137The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001138and actual outputs to be displayed using a context diff:
1139
Edward Loper71f55af2004-08-26 01:41:51 +00001140 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001141 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001142 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001143 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001144 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001145 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001146 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001147 Failed example:
1148 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001149 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001150 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001151 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001152 a
1153 ! B
1154 c
1155 d
1156 f
1157 g
1158 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001159 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001160 a
1161 ! b
1162 c
1163 d
1164 + e
1165 f
1166 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001167 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001168
1169
Edward Loper71f55af2004-08-26 01:41:51 +00001170The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001171used by the popular ndiff.py utility. This does intraline difference
1172marking, as well as interline differences.
1173
1174 >>> def f(x):
1175 ... r'''
1176 ... >>> print "a b c d e f g h i j k l m"
1177 ... a b c d e f g h i j k 1 m
1178 ... '''
1179 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001180 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001181 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001182 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001183 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001184 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001185 Failed example:
1186 print "a b c d e f g h i j k l m"
1187 Differences (ndiff with -expected +actual):
1188 - a b c d e f g h i j k 1 m
1189 ? ^
1190 + a b c d e f g h i j k l m
1191 ? + ++ ^
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001192 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001193
1194The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1195failing example:
1196
1197 >>> def f(x):
1198 ... r'''
1199 ... >>> print 1 # first success
1200 ... 1
1201 ... >>> print 2 # first failure
1202 ... 200
1203 ... >>> print 3 # second failure
1204 ... 300
1205 ... >>> print 4 # second success
1206 ... 4
1207 ... >>> print 5 # third failure
1208 ... 500
1209 ... '''
1210 >>> test = doctest.DocTestFinder().find(f)[0]
1211 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1212 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001213 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001214 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001215 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001216 Failed example:
1217 print 2 # first failure
1218 Expected:
1219 200
1220 Got:
1221 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001222 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001223
1224However, output from `report_start` is not supressed:
1225
1226 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001227 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001228 Trying:
1229 print 1 # first success
1230 Expecting:
1231 1
1232 ok
1233 Trying:
1234 print 2 # first failure
1235 Expecting:
1236 200
1237 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001238 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001239 Failed example:
1240 print 2 # first failure
1241 Expected:
1242 200
1243 Got:
1244 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001245 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001246
1247For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1248count as failures:
1249
1250 >>> def f(x):
1251 ... r'''
1252 ... >>> print 1 # first success
1253 ... 1
1254 ... >>> raise ValueError(2) # first failure
1255 ... 200
1256 ... >>> print 3 # second failure
1257 ... 300
1258 ... >>> print 4 # second success
1259 ... 4
1260 ... >>> print 5 # third failure
1261 ... 500
1262 ... '''
1263 >>> test = doctest.DocTestFinder().find(f)[0]
1264 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1265 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1266 ... # doctest: +ELLIPSIS
1267 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001268 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001269 Failed example:
1270 raise ValueError(2) # first failure
1271 Exception raised:
1272 ...
1273 ValueError: 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001274 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001275
Tim Petersad2ef332006-05-10 02:43:01 +00001276New option flags can also be registered, via register_optionflag(). Here
1277we reach into doctest's internals a bit.
1278
1279 >>> unlikely = "UNLIKELY_OPTION_NAME"
1280 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1281 False
1282 >>> new_flag_value = doctest.register_optionflag(unlikely)
1283 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1284 True
1285
1286Before 2.4.4/2.5, registering a name more than once erroneously created
1287more than one flag value. Here we verify that's fixed:
1288
1289 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1290 >>> redundant_flag_value == new_flag_value
1291 True
1292
1293Clean up.
1294 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1295
Tim Petersc6cbab02004-08-22 19:43:28 +00001296 """
1297
Tim Peters8485b562004-08-04 18:46:34 +00001298 def option_directives(): r"""
1299Tests of `DocTestRunner`'s option directive mechanism.
1300
Edward Loper74bca7a2004-08-12 02:27:44 +00001301Option directives can be used to turn option flags on or off for a
1302single example. To turn an option on for an example, follow that
1303example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001304
1305 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001306 ... >>> print range(10) # should fail: no ellipsis
1307 ... [0, 1, ..., 9]
1308 ...
1309 ... >>> print range(10) # doctest: +ELLIPSIS
1310 ... [0, 1, ..., 9]
1311 ... '''
1312 >>> test = doctest.DocTestFinder().find(f)[0]
1313 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001314 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001315 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001316 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001317 Failed example:
1318 print range(10) # should fail: no ellipsis
1319 Expected:
1320 [0, 1, ..., 9]
1321 Got:
1322 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001323 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001324
1325To turn an option off for an example, follow that example with a
1326comment of the form ``# doctest: -OPTION``:
1327
1328 >>> def f(x): r'''
1329 ... >>> print range(10)
1330 ... [0, 1, ..., 9]
1331 ...
1332 ... >>> # should fail: no ellipsis
1333 ... >>> print range(10) # doctest: -ELLIPSIS
1334 ... [0, 1, ..., 9]
1335 ... '''
1336 >>> test = doctest.DocTestFinder().find(f)[0]
1337 >>> doctest.DocTestRunner(verbose=False,
1338 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001339 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001340 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001341 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001342 Failed example:
1343 print range(10) # doctest: -ELLIPSIS
1344 Expected:
1345 [0, 1, ..., 9]
1346 Got:
1347 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001348 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001349
1350Option directives affect only the example that they appear with; they
1351do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001352
Edward Loper74bca7a2004-08-12 02:27:44 +00001353 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001354 ... >>> print range(10) # Should fail: no ellipsis
1355 ... [0, 1, ..., 9]
1356 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001357 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001358 ... [0, 1, ..., 9]
1359 ...
Tim Peters8485b562004-08-04 18:46:34 +00001360 ... >>> print range(10) # Should fail: no ellipsis
1361 ... [0, 1, ..., 9]
1362 ... '''
1363 >>> test = doctest.DocTestFinder().find(f)[0]
1364 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001365 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001366 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001367 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001368 Failed example:
1369 print range(10) # Should fail: no ellipsis
1370 Expected:
1371 [0, 1, ..., 9]
1372 Got:
1373 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001374 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001375 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001376 Failed example:
1377 print range(10) # Should fail: no ellipsis
1378 Expected:
1379 [0, 1, ..., 9]
1380 Got:
1381 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001382 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001383
Edward Loper74bca7a2004-08-12 02:27:44 +00001384Multiple options may be modified by a single option directive. They
1385may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001386
1387 >>> def f(x): r'''
1388 ... >>> print range(10) # Should fail
1389 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001390 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001391 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001392 ... [0, 1, ..., 9]
1393 ... '''
1394 >>> test = doctest.DocTestFinder().find(f)[0]
1395 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001396 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001397 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001398 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001399 Failed example:
1400 print range(10) # Should fail
1401 Expected:
1402 [0, 1, ..., 9]
1403 Got:
1404 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001405 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001406
1407 >>> def f(x): r'''
1408 ... >>> print range(10) # Should fail
1409 ... [0, 1, ..., 9]
1410 ... >>> print range(10) # Should succeed
1411 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1412 ... [0, 1, ..., 9]
1413 ... '''
1414 >>> test = doctest.DocTestFinder().find(f)[0]
1415 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001416 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001417 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001418 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001419 Failed example:
1420 print range(10) # Should fail
1421 Expected:
1422 [0, 1, ..., 9]
1423 Got:
1424 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001425 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001426
1427 >>> def f(x): r'''
1428 ... >>> print range(10) # Should fail
1429 ... [0, 1, ..., 9]
1430 ... >>> print range(10) # Should succeed
1431 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1432 ... [0, 1, ..., 9]
1433 ... '''
1434 >>> test = doctest.DocTestFinder().find(f)[0]
1435 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001436 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001437 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001438 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001439 Failed example:
1440 print range(10) # Should fail
1441 Expected:
1442 [0, 1, ..., 9]
1443 Got:
1444 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001445 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001446
1447The option directive may be put on the line following the source, as
1448long as a continuation prompt is used:
1449
1450 >>> def f(x): r'''
1451 ... >>> print range(10)
1452 ... ... # doctest: +ELLIPSIS
1453 ... [0, 1, ..., 9]
1454 ... '''
1455 >>> test = doctest.DocTestFinder().find(f)[0]
1456 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001457 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001458
Edward Loper74bca7a2004-08-12 02:27:44 +00001459For examples with multi-line source, the option directive may appear
1460at the end of any line:
1461
1462 >>> def f(x): r'''
1463 ... >>> for x in range(10): # doctest: +ELLIPSIS
1464 ... ... print x,
1465 ... 0 1 2 ... 9
1466 ...
1467 ... >>> for x in range(10):
1468 ... ... print x, # doctest: +ELLIPSIS
1469 ... 0 1 2 ... 9
1470 ... '''
1471 >>> test = doctest.DocTestFinder().find(f)[0]
1472 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001473 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001474
1475If more than one line of an example with multi-line source has an
1476option directive, then they are combined:
1477
1478 >>> def f(x): r'''
1479 ... Should fail (option directive not on the last line):
1480 ... >>> for x in range(10): # doctest: +ELLIPSIS
1481 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1482 ... 0 1 2...9
1483 ... '''
1484 >>> test = doctest.DocTestFinder().find(f)[0]
1485 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001486 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001487
1488It is an error to have a comment of the form ``# doctest:`` that is
1489*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1490``OPTION`` is an option that has been registered with
1491`register_option`:
1492
1493 >>> # Error: Option not registered
1494 >>> s = '>>> print 12 #doctest: +BADOPTION'
1495 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1496 Traceback (most recent call last):
1497 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1498
1499 >>> # Error: No + or - prefix
1500 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1501 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1502 Traceback (most recent call last):
1503 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1504
1505It is an error to use an option directive on a line that contains no
1506source:
1507
1508 >>> s = '>>> # doctest: +ELLIPSIS'
1509 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1510 Traceback (most recent call last):
1511 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 +00001512"""
1513
1514def test_testsource(): r"""
1515Unit tests for `testsource()`.
1516
1517The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001518test with that name in that module, and converts it to a script. The
1519example code is converted to regular Python code. The surrounding
1520words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001521
1522 >>> import test.test_doctest
1523 >>> name = 'test.test_doctest.sample_func'
1524 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001525 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001526 #
Tim Peters8485b562004-08-04 18:46:34 +00001527 print sample_func(22)
1528 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001529 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001530 #
Edward Lopera5db6002004-08-12 02:41:30 +00001531 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001532 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001533
1534 >>> name = 'test.test_doctest.SampleNewStyleClass'
1535 >>> print doctest.testsource(test.test_doctest, name)
1536 print '1\n2\n3'
1537 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001538 ## 1
1539 ## 2
1540 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001541 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001542
1543 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1544 >>> print doctest.testsource(test.test_doctest, name)
1545 print SampleClass.a_classmethod(10)
1546 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001547 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001548 print SampleClass(0).a_classmethod(10)
1549 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001550 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001551 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001552"""
1553
1554def test_debug(): r"""
1555
1556Create a docstring that we want to debug:
1557
1558 >>> s = '''
1559 ... >>> x = 12
1560 ... >>> print x
1561 ... 12
1562 ... '''
1563
1564Create some fake stdin input, to feed to the debugger:
1565
1566 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001567 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001568 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001569
1570Run the debugger on the docstring, and then restore sys.stdin.
1571
Edward Loper2de91ba2004-08-27 02:07:46 +00001572 >>> try: doctest.debug_src(s)
1573 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001574 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001575 (Pdb) next
1576 12
Tim Peters8485b562004-08-04 18:46:34 +00001577 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001578 > <string>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001579 (Pdb) print x
1580 12
1581 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001582
1583"""
1584
Jim Fulton356fd192004-08-09 11:34:47 +00001585def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001586 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001587
Tim Peters413ced62004-08-09 15:43:47 +00001588 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001589 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001590 you use it. The doctest module changes sys.stdout so that it can
1591 capture program output. It also temporarily replaces pdb.set_trace
1592 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001593 see debugger output.
1594
1595 >>> doc = '''
1596 ... >>> x = 42
1597 ... >>> import pdb; pdb.set_trace()
1598 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001599 >>> parser = doctest.DocTestParser()
1600 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001601 >>> runner = doctest.DocTestRunner(verbose=False)
1602
1603 To demonstrate this, we'll create a fake standard input that
1604 captures our debugger input:
1605
1606 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001607 >>> real_stdin = sys.stdin
1608 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001609 ... 'print x', # print data defined by the example
1610 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001611 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001612
Edward Loper2de91ba2004-08-27 02:07:46 +00001613 >>> try: runner.run(test)
1614 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001615 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001616 > <doctest foo[1]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001617 -> import pdb; pdb.set_trace()
1618 (Pdb) print x
1619 42
1620 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001621 TestResults(failed=0, attempted=2)
Jim Fulton356fd192004-08-09 11:34:47 +00001622
1623 You can also put pdb.set_trace in a function called from a test:
1624
1625 >>> def calls_set_trace():
1626 ... y=2
1627 ... import pdb; pdb.set_trace()
1628
1629 >>> doc = '''
1630 ... >>> x=1
1631 ... >>> calls_set_trace()
1632 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001633 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001634 >>> real_stdin = sys.stdin
1635 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001636 ... 'print y', # print data defined in the function
1637 ... 'up', # out of function
1638 ... 'print x', # print data defined by the example
1639 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001640 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001641
Tim Peters50c6bdb2004-11-08 22:07:37 +00001642 >>> try:
1643 ... runner.run(test)
1644 ... finally:
1645 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001646 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001647 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1648 -> import pdb; pdb.set_trace()
1649 (Pdb) print y
1650 2
1651 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001652 > <doctest foo[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001653 -> calls_set_trace()
1654 (Pdb) print x
1655 1
1656 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001657 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001658
1659 During interactive debugging, source code is shown, even for
1660 doctest examples:
1661
1662 >>> doc = '''
1663 ... >>> def f(x):
1664 ... ... g(x*2)
1665 ... >>> def g(x):
1666 ... ... print x+3
1667 ... ... import pdb; pdb.set_trace()
1668 ... >>> f(3)
1669 ... '''
1670 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1671 >>> real_stdin = sys.stdin
1672 >>> sys.stdin = _FakeInput([
1673 ... 'list', # list source from example 2
1674 ... 'next', # return from g()
1675 ... 'list', # list source from example 1
1676 ... 'next', # return from f()
1677 ... 'list', # list source from example 3
1678 ... 'continue', # stop debugging
1679 ... ''])
1680 >>> try: runner.run(test)
1681 ... finally: sys.stdin = real_stdin
1682 ... # doctest: +NORMALIZE_WHITESPACE
1683 --Return--
1684 > <doctest foo[1]>(3)g()->None
1685 -> import pdb; pdb.set_trace()
1686 (Pdb) list
1687 1 def g(x):
1688 2 print x+3
1689 3 -> import pdb; pdb.set_trace()
1690 [EOF]
1691 (Pdb) next
1692 --Return--
1693 > <doctest foo[0]>(2)f()->None
1694 -> g(x*2)
1695 (Pdb) list
1696 1 def f(x):
1697 2 -> g(x*2)
1698 [EOF]
1699 (Pdb) next
1700 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701 > <doctest foo[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001702 -> f(3)
1703 (Pdb) list
1704 1 -> f(3)
1705 [EOF]
1706 (Pdb) continue
1707 **********************************************************************
1708 File "foo.py", line 7, in foo
1709 Failed example:
1710 f(3)
1711 Expected nothing
1712 Got:
1713 9
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001714 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001715 """
1716
Tim Peters50c6bdb2004-11-08 22:07:37 +00001717def test_pdb_set_trace_nested():
1718 """This illustrates more-demanding use of set_trace with nested functions.
1719
1720 >>> class C(object):
1721 ... def calls_set_trace(self):
1722 ... y = 1
1723 ... import pdb; pdb.set_trace()
1724 ... self.f1()
1725 ... y = 2
1726 ... def f1(self):
1727 ... x = 1
1728 ... self.f2()
1729 ... x = 2
1730 ... def f2(self):
1731 ... z = 1
1732 ... z = 2
1733
1734 >>> calls_set_trace = C().calls_set_trace
1735
1736 >>> doc = '''
1737 ... >>> a = 1
1738 ... >>> calls_set_trace()
1739 ... '''
1740 >>> parser = doctest.DocTestParser()
1741 >>> runner = doctest.DocTestRunner(verbose=False)
1742 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1743 >>> real_stdin = sys.stdin
1744 >>> sys.stdin = _FakeInput([
1745 ... 'print y', # print data defined in the function
1746 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z',
1747 ... 'up', 'print x',
1748 ... 'up', 'print y',
1749 ... 'up', 'print foo',
1750 ... 'continue', # stop debugging
1751 ... ''])
1752
1753 >>> try:
1754 ... runner.run(test)
1755 ... finally:
1756 ... sys.stdin = real_stdin
1757 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1758 -> self.f1()
1759 (Pdb) print y
1760 1
1761 (Pdb) step
1762 --Call--
1763 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1764 -> def f1(self):
1765 (Pdb) step
1766 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1767 -> x = 1
1768 (Pdb) step
1769 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1770 -> self.f2()
1771 (Pdb) step
1772 --Call--
1773 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1774 -> def f2(self):
1775 (Pdb) step
1776 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1777 -> z = 1
1778 (Pdb) step
1779 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1780 -> z = 2
1781 (Pdb) print z
1782 1
1783 (Pdb) up
1784 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1785 -> self.f2()
1786 (Pdb) print x
1787 1
1788 (Pdb) up
1789 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1790 -> self.f1()
1791 (Pdb) print y
1792 1
1793 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001794 > <doctest foo[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001795 -> calls_set_trace()
1796 (Pdb) print foo
1797 *** NameError: name 'foo' is not defined
1798 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001799 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001800"""
1801
Tim Peters19397e52004-08-06 22:02:59 +00001802def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001803 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001804
1805 We create a Suite by providing a module. A module can be provided
1806 by passing a module object:
1807
1808 >>> import unittest
1809 >>> import test.sample_doctest
1810 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1811 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001812 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001813
1814 We can also supply the module by name:
1815
1816 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1817 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001818 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001819
1820 We can use the current module:
1821
1822 >>> suite = test.sample_doctest.test_suite()
1823 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001824 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001825
1826 We can supply global variables. If we pass globs, they will be
1827 used instead of the module globals. Here we'll pass an empty
1828 globals, triggering an extra error:
1829
1830 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1831 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001832 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001833
1834 Alternatively, we can provide extra globals. Here we'll make an
1835 error go away by providing an extra global variable:
1836
1837 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1838 ... extraglobs={'y': 1})
1839 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001840 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001841
1842 You can pass option flags. Here we'll cause an extra error
1843 by disabling the blank-line feature:
1844
1845 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001846 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001847 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001848 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001849
Tim Peters1e277ee2004-08-07 05:37:52 +00001850 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001851
Jim Fultonf54bad42004-08-28 14:57:56 +00001852 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001853 ... import test.test_doctest
1854 ... test.test_doctest.sillySetup = True
1855
Jim Fultonf54bad42004-08-28 14:57:56 +00001856 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001857 ... import test.test_doctest
1858 ... del test.test_doctest.sillySetup
1859
1860 Here, we installed a silly variable that the test expects:
1861
1862 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1863 ... setUp=setUp, tearDown=tearDown)
1864 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001865 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001866
1867 But the tearDown restores sanity:
1868
1869 >>> import test.test_doctest
1870 >>> test.test_doctest.sillySetup
1871 Traceback (most recent call last):
1872 ...
1873 AttributeError: 'module' object has no attribute 'sillySetup'
1874
Jim Fultonf54bad42004-08-28 14:57:56 +00001875 The setUp and tearDown funtions are passed test objects. Here
1876 we'll use the setUp function to supply the missing variable y:
1877
1878 >>> def setUp(test):
1879 ... test.globs['y'] = 1
1880
1881 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1882 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001883 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00001884
1885 Here, we didn't need to use a tearDown function because we
1886 modified the test globals, which are a copy of the
1887 sample_doctest module dictionary. The test globals are
1888 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001889 """
1890
1891def test_DocFileSuite():
1892 """We can test tests found in text files using a DocFileSuite.
1893
1894 We create a suite by providing the names of one or more text
1895 files that include examples:
1896
1897 >>> import unittest
1898 >>> suite = doctest.DocFileSuite('test_doctest.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00001899 ... 'test_doctest2.txt',
1900 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00001901 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001902 <unittest.result.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001903
1904 The test files are looked for in the directory containing the
1905 calling module. A package keyword argument can be provided to
1906 specify a different relative location.
1907
1908 >>> import unittest
1909 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1910 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00001911 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001912 ... package='test')
1913 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001914 <unittest.result.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001915
Brett Cannon43e53f82007-11-21 00:47:36 +00001916 Support for using a package's __loader__.get_data() is also
1917 provided.
1918
1919 >>> import unittest, pkgutil, test
Brett Cannoneaa2c982007-11-23 00:06:51 +00001920 >>> added_loader = False
Brett Cannon43e53f82007-11-21 00:47:36 +00001921 >>> if not hasattr(test, '__loader__'):
1922 ... test.__loader__ = pkgutil.get_loader(test)
1923 ... added_loader = True
1924 >>> try:
1925 ... suite = doctest.DocFileSuite('test_doctest.txt',
1926 ... 'test_doctest2.txt',
1927 ... 'test_doctest4.txt',
1928 ... package='test')
1929 ... suite.run(unittest.TestResult())
1930 ... finally:
Brett Cannon9db1d5a2007-11-21 00:58:03 +00001931 ... if added_loader:
1932 ... del test.__loader__
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001933 <unittest.result.TestResult run=3 errors=0 failures=3>
Brett Cannon43e53f82007-11-21 00:47:36 +00001934
Edward Loper0273f5b2004-09-18 20:27:04 +00001935 '/' should be used as a path separator. It will be converted
1936 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001937
1938 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1939 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001940 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001941
Edward Loper0273f5b2004-09-18 20:27:04 +00001942 If DocFileSuite is used from an interactive session, then files
1943 are resolved relative to the directory of sys.argv[0]:
1944
Christian Heimesc756d002007-11-27 21:34:01 +00001945 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00001946 >>> save_argv = sys.argv
1947 >>> sys.argv = [test.test_doctest.__file__]
1948 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimesc756d002007-11-27 21:34:01 +00001949 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00001950 >>> sys.argv = save_argv
1951
Edward Loper052d0cd2004-09-19 17:19:33 +00001952 By setting `module_relative=False`, os-specific paths may be
1953 used (including absolute paths and paths relative to the
1954 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00001955
1956 >>> # Get the absolute path of the test package.
1957 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
1958 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
1959
1960 >>> # Use it to find the absolute path of test_doctest.txt.
1961 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
1962
Edward Loper052d0cd2004-09-19 17:19:33 +00001963 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00001964 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001965 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00001966
Edward Loper052d0cd2004-09-19 17:19:33 +00001967 It is an error to specify `package` when `module_relative=False`:
1968
1969 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
1970 ... package='test')
1971 Traceback (most recent call last):
1972 ValueError: Package may only be specified for module-relative paths.
1973
Tim Peters19397e52004-08-06 22:02:59 +00001974 You can specify initial global variables:
1975
1976 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1977 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00001978 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001979 ... globs={'favorite_color': 'blue'})
1980 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001981 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001982
1983 In this case, we supplied a missing favorite color. You can
1984 provide doctest options:
1985
1986 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1987 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00001988 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001989 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1990 ... globs={'favorite_color': 'blue'})
1991 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001992 <unittest.result.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001993
1994 And, you can provide setUp and tearDown functions:
1995
Jim Fultonf54bad42004-08-28 14:57:56 +00001996 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001997 ... import test.test_doctest
1998 ... test.test_doctest.sillySetup = True
1999
Jim Fultonf54bad42004-08-28 14:57:56 +00002000 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002001 ... import test.test_doctest
2002 ... del test.test_doctest.sillySetup
2003
2004 Here, we installed a silly variable that the test expects:
2005
2006 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2007 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002008 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002009 ... setUp=setUp, tearDown=tearDown)
2010 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002011 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002012
2013 But the tearDown restores sanity:
2014
2015 >>> import test.test_doctest
2016 >>> test.test_doctest.sillySetup
2017 Traceback (most recent call last):
2018 ...
2019 AttributeError: 'module' object has no attribute 'sillySetup'
2020
Jim Fultonf54bad42004-08-28 14:57:56 +00002021 The setUp and tearDown funtions are passed test objects.
2022 Here, we'll use a setUp function to set the favorite color in
2023 test_doctest.txt:
2024
2025 >>> def setUp(test):
2026 ... test.globs['favorite_color'] = 'blue'
2027
2028 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2029 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002030 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002031
2032 Here, we didn't need to use a tearDown function because we
2033 modified the test globals. The test globals are
2034 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002035
Fred Drake7c404a42004-12-21 23:46:34 +00002036 Tests in a file run using `DocFileSuite` can also access the
2037 `__file__` global, which is set to the name of the file
2038 containing the tests:
2039
2040 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2041 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002042 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002043
George Yoshidaf3c65de2006-05-28 16:39:09 +00002044 If the tests contain non-ASCII characters, we have to specify which
2045 encoding the file is encoded with. We do so by using the `encoding`
2046 parameter:
2047
2048 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2049 ... 'test_doctest2.txt',
2050 ... 'test_doctest4.txt',
2051 ... encoding='utf-8')
2052 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002053 <unittest.result.TestResult run=3 errors=0 failures=2>
George Yoshidaf3c65de2006-05-28 16:39:09 +00002054
Jim Fultonf54bad42004-08-28 14:57:56 +00002055 """
Tim Peters19397e52004-08-06 22:02:59 +00002056
Jim Fulton07a349c2004-08-22 14:10:00 +00002057def test_trailing_space_in_test():
2058 """
Tim Petersa7def722004-08-23 22:13:22 +00002059 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002060
Jim Fulton07a349c2004-08-22 14:10:00 +00002061 >>> x, y = 'foo', ''
2062 >>> print x, y
2063 foo \n
2064 """
Tim Peters19397e52004-08-06 22:02:59 +00002065
Jim Fultonf54bad42004-08-28 14:57:56 +00002066
2067def test_unittest_reportflags():
2068 """Default unittest reporting flags can be set to control reporting
2069
2070 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2071 only the first failure of each test. First, we'll look at the
2072 output without the flag. The file test_doctest.txt file has two
2073 tests. They both fail if blank lines are disabled:
2074
2075 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2076 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2077 >>> import unittest
2078 >>> result = suite.run(unittest.TestResult())
2079 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2080 Traceback ...
2081 Failed example:
2082 favorite_color
2083 ...
2084 Failed example:
2085 if 1:
2086 ...
2087
2088 Note that we see both failures displayed.
2089
2090 >>> old = doctest.set_unittest_reportflags(
2091 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2092
2093 Now, when we run the test:
2094
2095 >>> result = suite.run(unittest.TestResult())
2096 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2097 Traceback ...
2098 Failed example:
2099 favorite_color
2100 Exception raised:
2101 ...
2102 NameError: name 'favorite_color' is not defined
2103 <BLANKLINE>
2104 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002105
Jim Fultonf54bad42004-08-28 14:57:56 +00002106 We get only the first failure.
2107
2108 If we give any reporting options when we set up the tests,
2109 however:
2110
2111 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2112 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2113
2114 Then the default eporting options are ignored:
2115
2116 >>> result = suite.run(unittest.TestResult())
2117 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2118 Traceback ...
2119 Failed example:
2120 favorite_color
2121 ...
2122 Failed example:
2123 if 1:
2124 print 'a'
2125 print
2126 print 'b'
2127 Differences (ndiff with -expected +actual):
2128 a
2129 - <BLANKLINE>
2130 +
2131 b
2132 <BLANKLINE>
2133 <BLANKLINE>
2134
2135
2136 Test runners can restore the formatting flags after they run:
2137
2138 >>> ignored = doctest.set_unittest_reportflags(old)
2139
2140 """
2141
Edward Loper052d0cd2004-09-19 17:19:33 +00002142def test_testfile(): r"""
2143Tests for the `testfile()` function. This function runs all the
2144doctest examples in a given file. In its simple invokation, it is
2145called with the name of a file, which is taken to be relative to the
2146calling module. The return value is (#failures, #tests).
2147
2148 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2149 **********************************************************************
2150 File "...", line 6, in test_doctest.txt
2151 Failed example:
2152 favorite_color
2153 Exception raised:
2154 ...
2155 NameError: name 'favorite_color' is not defined
2156 **********************************************************************
2157 1 items had failures:
2158 1 of 2 in test_doctest.txt
2159 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002160 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002161 >>> doctest.master = None # Reset master.
2162
2163(Note: we'll be clearing doctest.master after each call to
2164`doctest.testfile`, to supress warnings about multiple tests with the
2165same name.)
2166
2167Globals may be specified with the `globs` and `extraglobs` parameters:
2168
2169 >>> globs = {'favorite_color': 'blue'}
2170 >>> doctest.testfile('test_doctest.txt', globs=globs)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002171 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002172 >>> doctest.master = None # Reset master.
2173
2174 >>> extraglobs = {'favorite_color': 'red'}
2175 >>> doctest.testfile('test_doctest.txt', globs=globs,
2176 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2177 **********************************************************************
2178 File "...", line 6, in test_doctest.txt
2179 Failed example:
2180 favorite_color
2181 Expected:
2182 'blue'
2183 Got:
2184 'red'
2185 **********************************************************************
2186 1 items had failures:
2187 1 of 2 in test_doctest.txt
2188 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002189 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002190 >>> doctest.master = None # Reset master.
2191
2192The file may be made relative to a given module or package, using the
2193optional `module_relative` parameter:
2194
2195 >>> doctest.testfile('test_doctest.txt', globs=globs,
2196 ... module_relative='test')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002197 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002198 >>> doctest.master = None # Reset master.
2199
2200Verbosity can be increased with the optional `verbose` paremter:
2201
2202 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2203 Trying:
2204 favorite_color
2205 Expecting:
2206 'blue'
2207 ok
2208 Trying:
2209 if 1:
2210 print 'a'
2211 print
2212 print 'b'
2213 Expecting:
2214 a
2215 <BLANKLINE>
2216 b
2217 ok
2218 1 items passed all tests:
2219 2 tests in test_doctest.txt
2220 2 tests in 1 items.
2221 2 passed and 0 failed.
2222 Test passed.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002223 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002224 >>> doctest.master = None # Reset master.
2225
2226The name of the test may be specified with the optional `name`
2227parameter:
2228
2229 >>> doctest.testfile('test_doctest.txt', name='newname')
2230 ... # doctest: +ELLIPSIS
2231 **********************************************************************
2232 File "...", line 6, in newname
2233 ...
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002234 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002235 >>> doctest.master = None # Reset master.
2236
2237The summary report may be supressed with the optional `report`
2238parameter:
2239
2240 >>> doctest.testfile('test_doctest.txt', report=False)
2241 ... # doctest: +ELLIPSIS
2242 **********************************************************************
2243 File "...", line 6, in test_doctest.txt
2244 Failed example:
2245 favorite_color
2246 Exception raised:
2247 ...
2248 NameError: name 'favorite_color' is not defined
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002249 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002250 >>> doctest.master = None # Reset master.
2251
2252The optional keyword argument `raise_on_error` can be used to raise an
2253exception on the first error (which may be useful for postmortem
2254debugging):
2255
2256 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2257 ... # doctest: +ELLIPSIS
2258 Traceback (most recent call last):
2259 UnexpectedException: ...
2260 >>> doctest.master = None # Reset master.
George Yoshidaf3c65de2006-05-28 16:39:09 +00002261
2262If the tests contain non-ASCII characters, the tests might fail, since
2263it's unknown which encoding is used. The encoding can be specified
2264using the optional keyword argument `encoding`:
2265
2266 >>> doctest.testfile('test_doctest4.txt') # doctest: +ELLIPSIS
2267 **********************************************************************
2268 File "...", line 7, in test_doctest4.txt
2269 Failed example:
2270 u'...'
2271 Expected:
2272 u'f\xf6\xf6'
2273 Got:
2274 u'f\xc3\xb6\xc3\xb6'
2275 **********************************************************************
2276 ...
2277 **********************************************************************
2278 1 items had failures:
2279 2 of 4 in test_doctest4.txt
2280 ***Test Failed*** 2 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002281 TestResults(failed=2, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002282 >>> doctest.master = None # Reset master.
2283
2284 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002285 TestResults(failed=0, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002286 >>> doctest.master = None # Reset master.
Edward Loper052d0cd2004-09-19 17:19:33 +00002287"""
2288
Tim Petersa7def722004-08-23 22:13:22 +00002289# old_test1, ... used to live in doctest.py, but cluttered it. Note
2290# that these use the deprecated doctest.Tester, so should go away (or
2291# be rewritten) someday.
2292
2293# Ignore all warnings about the use of class Tester in this module.
2294# Note that the name of this module may differ depending on how it's
2295# imported, so the use of __name__ is important.
2296warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2297 __name__, 0)
2298
2299def old_test1(): r"""
2300>>> from doctest import Tester
2301>>> t = Tester(globs={'x': 42}, verbose=0)
2302>>> t.runstring(r'''
2303... >>> x = x * 2
2304... >>> print x
2305... 42
2306... ''', 'XYZ')
2307**********************************************************************
2308Line 3, in XYZ
2309Failed example:
2310 print x
2311Expected:
2312 42
2313Got:
2314 84
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002315TestResults(failed=1, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002316>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002317TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002318>>> t.summarize()
2319**********************************************************************
23201 items had failures:
2321 1 of 2 in XYZ
2322***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002323TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002324>>> t.summarize(verbose=1)
23251 items passed all tests:
2326 2 tests in example2
2327**********************************************************************
23281 items had failures:
2329 1 of 2 in XYZ
23304 tests in 2 items.
23313 passed and 1 failed.
2332***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002333TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002334"""
2335
2336def old_test2(): r"""
2337 >>> from doctest import Tester
2338 >>> t = Tester(globs={}, verbose=1)
2339 >>> test = r'''
2340 ... # just an example
2341 ... >>> x = 1 + 2
2342 ... >>> x
2343 ... 3
2344 ... '''
2345 >>> t.runstring(test, "Example")
2346 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002347 Trying:
2348 x = 1 + 2
2349 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002350 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002351 Trying:
2352 x
2353 Expecting:
2354 3
Tim Petersa7def722004-08-23 22:13:22 +00002355 ok
2356 0 of 2 examples failed in string Example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002357 TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002358"""
2359
2360def old_test3(): r"""
2361 >>> from doctest import Tester
2362 >>> t = Tester(globs={}, verbose=0)
2363 >>> def _f():
2364 ... '''Trivial docstring example.
2365 ... >>> assert 2 == 2
2366 ... '''
2367 ... return 32
2368 ...
2369 >>> t.rundoc(_f) # expect 0 failures in 1 example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002370 TestResults(failed=0, attempted=1)
Tim Petersa7def722004-08-23 22:13:22 +00002371"""
2372
2373def old_test4(): """
Christian Heimesc756d002007-11-27 21:34:01 +00002374 >>> import types
2375 >>> m1 = types.ModuleType('_m1')
2376 >>> m2 = types.ModuleType('_m2')
Tim Petersa7def722004-08-23 22:13:22 +00002377 >>> test_data = \"""
2378 ... def _f():
2379 ... '''>>> assert 1 == 1
2380 ... '''
2381 ... def g():
2382 ... '''>>> assert 2 != 1
2383 ... '''
2384 ... class H:
2385 ... '''>>> assert 2 > 1
2386 ... '''
2387 ... def bar(self):
2388 ... '''>>> assert 1 < 2
2389 ... '''
2390 ... \"""
2391 >>> exec test_data in m1.__dict__
2392 >>> exec test_data in m2.__dict__
2393 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2394
2395 Tests that objects outside m1 are excluded:
2396
2397 >>> from doctest import Tester
2398 >>> t = Tester(globs={}, verbose=0)
2399 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002400 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002401
2402 Once more, not excluding stuff outside m1:
2403
2404 >>> t = Tester(globs={}, verbose=0)
2405 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002406 TestResults(failed=0, attempted=8)
Tim Petersa7def722004-08-23 22:13:22 +00002407
2408 The exclusion of objects from outside the designated module is
2409 meant to be invoked automagically by testmod.
2410
2411 >>> doctest.testmod(m1, verbose=False)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002412 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002413"""
2414
Tim Peters8485b562004-08-04 18:46:34 +00002415######################################################################
2416## Main
2417######################################################################
2418
2419def test_main():
2420 # Check the doctest cases in doctest itself:
2421 test_support.run_doctest(doctest, verbosity=True)
2422 # Check the doctest cases defined here:
2423 from test import test_doctest
2424 test_support.run_doctest(test_doctest, verbosity=True)
2425
Christian Heimesc5f05e42008-02-23 17:40:11 +00002426import trace, sys
Tim Peters8485b562004-08-04 18:46:34 +00002427def test_coverage(coverdir):
2428 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2429 trace=0, count=1)
2430 tracer.run('reload(doctest); test_main()')
2431 r = tracer.results()
2432 print 'Writing coverage results...'
2433 r.write_results(show_missing=True, summary=True,
2434 coverdir=coverdir)
2435
2436if __name__ == '__main__':
2437 if '-c' in sys.argv:
2438 test_coverage('/tmp/doctest.cover')
2439 else:
2440 test_main()