blob: a8128687b196d2ac3aec8c375b0651590600410d [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
Edward Loper32ddbf72004-09-13 05:47:24 +0000501 >>> tests = excl_empty_finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000502 >>> print len(tests)
503 2
504 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000505 test.doctest_aliases.TwoNames
506
507 TwoNames.f and TwoNames.g are bound to the same object.
508 We can't guess which will be found in doctest's traversal of
509 TwoNames.__dict__ first, so we have to allow for either.
510
511 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000512 True
513
Tim Petersbf0400a2006-06-05 01:43:03 +0000514Empty Tests
515~~~~~~~~~~~
516By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000517
Tim Petersbf0400a2006-06-05 01:43:03 +0000518 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000519 >>> for t in tests:
520 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000521 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000522 3 SampleClass.NestedClass
523 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000524 1 SampleClass.__init__
Tim Petersbf0400a2006-06-05 01:43:03 +0000525 2 SampleClass.a_classmethod
526 1 SampleClass.a_property
527 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000528 1 SampleClass.double
529 1 SampleClass.get
530
531By default, that excluded objects with no doctests. exclude_empty=False
532tells it to include (empty) tests for objects with no doctests. This feature
533is really to support backward compatibility in what doctest.master.summarize()
534displays.
535
Tim Petersbf0400a2006-06-05 01:43:03 +0000536 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000537 >>> for t in tests:
538 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000539 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000540 3 SampleClass.NestedClass
541 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000542 0 SampleClass.NestedClass.get
543 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000544 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000545 2 SampleClass.a_classmethod
546 1 SampleClass.a_property
547 1 SampleClass.a_staticmethod
548 1 SampleClass.double
549 1 SampleClass.get
550
Tim Peters8485b562004-08-04 18:46:34 +0000551Turning off Recursion
552~~~~~~~~~~~~~~~~~~~~~
553DocTestFinder can be told not to look for tests in contained objects
554using the `recurse` flag:
555
556 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000557 >>> for t in tests:
558 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000559 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000560
561Line numbers
562~~~~~~~~~~~~
563DocTestFinder finds the line number of each example:
564
565 >>> def f(x):
566 ... '''
567 ... >>> x = 12
568 ...
569 ... some text
570 ...
571 ... >>> # examples are not created for comments & bare prompts.
572 ... >>>
573 ... ...
574 ...
575 ... >>> for x in range(10):
576 ... ... print x,
577 ... 0 1 2 3 4 5 6 7 8 9
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000578 ... >>> x//2
Edward Loperb51b2342004-08-17 16:37:12 +0000579 ... 6
580 ... '''
581 >>> test = doctest.DocTestFinder().find(f)[0]
582 >>> [e.lineno for e in test.examples]
583 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000584"""
585
Edward Loper00f8da72004-08-26 18:05:07 +0000586def test_DocTestParser(): r"""
587Unit tests for the `DocTestParser` class.
588
589DocTestParser is used to parse docstrings containing doctest examples.
590
591The `parse` method divides a docstring into examples and intervening
592text:
593
594 >>> s = '''
595 ... >>> x, y = 2, 3 # no output expected
596 ... >>> if 1:
597 ... ... print x
598 ... ... print y
599 ... 2
600 ... 3
601 ...
602 ... Some text.
603 ... >>> x+y
604 ... 5
605 ... '''
606 >>> parser = doctest.DocTestParser()
607 >>> for piece in parser.parse(s):
608 ... if isinstance(piece, doctest.Example):
609 ... print 'Example:', (piece.source, piece.want, piece.lineno)
610 ... else:
611 ... print ' Text:', `piece`
612 Text: '\n'
613 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
614 Text: ''
615 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
616 Text: '\nSome text.\n'
617 Example: ('x+y\n', '5\n', 9)
618 Text: ''
619
620The `get_examples` method returns just the examples:
621
622 >>> for piece in parser.get_examples(s):
623 ... print (piece.source, piece.want, piece.lineno)
624 ('x, y = 2, 3 # no output expected\n', '', 1)
625 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
626 ('x+y\n', '5\n', 9)
627
628The `get_doctest` method creates a Test from the examples, along with the
629given arguments:
630
631 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
632 >>> (test.name, test.filename, test.lineno)
633 ('name', 'filename', 5)
634 >>> for piece in test.examples:
635 ... print (piece.source, piece.want, piece.lineno)
636 ('x, y = 2, 3 # no output expected\n', '', 1)
637 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
638 ('x+y\n', '5\n', 9)
639"""
640
Tim Peters8485b562004-08-04 18:46:34 +0000641class test_DocTestRunner:
642 def basics(): r"""
643Unit tests for the `DocTestRunner` class.
644
645DocTestRunner is used to run DocTest test cases, and to accumulate
646statistics. Here's a simple DocTest case we can use:
647
648 >>> def f(x):
649 ... '''
650 ... >>> x = 12
651 ... >>> print x
652 ... 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000653 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000654 ... 6
655 ... '''
656 >>> test = doctest.DocTestFinder().find(f)[0]
657
658The main DocTestRunner interface is the `run` method, which runs a
659given DocTest case in a given namespace (globs). It returns a tuple
660`(f,t)`, where `f` is the number of failed tests and `t` is the number
661of tried tests.
662
663 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000664 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000665
666If any example produces incorrect output, then the test runner reports
667the failure and proceeds to the next example:
668
669 >>> def f(x):
670 ... '''
671 ... >>> x = 12
672 ... >>> print x
673 ... 14
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000674 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000675 ... 6
676 ... '''
677 >>> test = doctest.DocTestFinder().find(f)[0]
678 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000679 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000680 Trying:
681 x = 12
682 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000683 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000684 Trying:
685 print x
686 Expecting:
687 14
Tim Peters8485b562004-08-04 18:46:34 +0000688 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000689 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000690 Failed example:
691 print x
692 Expected:
693 14
694 Got:
695 12
Edward Loperaacf0832004-08-26 01:19:50 +0000696 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000697 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000698 Expecting:
699 6
Tim Peters8485b562004-08-04 18:46:34 +0000700 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000701 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000702"""
703 def verbose_flag(): r"""
704The `verbose` flag makes the test runner generate more detailed
705output:
706
707 >>> def f(x):
708 ... '''
709 ... >>> x = 12
710 ... >>> print x
711 ... 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000712 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000713 ... 6
714 ... '''
715 >>> test = doctest.DocTestFinder().find(f)[0]
716
717 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000718 Trying:
719 x = 12
720 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000721 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000722 Trying:
723 print x
724 Expecting:
725 12
Tim Peters8485b562004-08-04 18:46:34 +0000726 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000727 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000728 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000729 Expecting:
730 6
Tim Peters8485b562004-08-04 18:46:34 +0000731 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000732 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000733
734If the `verbose` flag is unspecified, then the output will be verbose
735iff `-v` appears in sys.argv:
736
737 >>> # Save the real sys.argv list.
738 >>> old_argv = sys.argv
739
740 >>> # If -v does not appear in sys.argv, then output isn't verbose.
741 >>> sys.argv = ['test']
742 >>> doctest.DocTestRunner().run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000743 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000744
745 >>> # If -v does appear in sys.argv, then output is verbose.
746 >>> sys.argv = ['test', '-v']
747 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000748 Trying:
749 x = 12
750 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000751 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000752 Trying:
753 print x
754 Expecting:
755 12
Tim Peters8485b562004-08-04 18:46:34 +0000756 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000757 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000758 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000759 Expecting:
760 6
Tim Peters8485b562004-08-04 18:46:34 +0000761 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000762 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000763
764 >>> # Restore sys.argv
765 >>> sys.argv = old_argv
766
767In the remaining examples, the test runner's verbosity will be
768explicitly set, to ensure that the test behavior is consistent.
769 """
770 def exceptions(): r"""
771Tests of `DocTestRunner`'s exception handling.
772
773An expected exception is specified with a traceback message. The
774lines between the first line and the type/value may be omitted or
775replaced with any other string:
776
777 >>> def f(x):
778 ... '''
779 ... >>> x = 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000780 ... >>> print x//0
Tim Peters8485b562004-08-04 18:46:34 +0000781 ... Traceback (most recent call last):
782 ... ZeroDivisionError: integer division or modulo by zero
783 ... '''
784 >>> test = doctest.DocTestFinder().find(f)[0]
785 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000786 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000787
Edward Loper19b19582004-08-25 23:07:03 +0000788An example may not generate output before it raises an exception; if
789it does, then the traceback message will not be recognized as
790signaling an expected exception, so the example will be reported as an
791unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000792
793 >>> def f(x):
794 ... '''
795 ... >>> x = 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000796 ... >>> print 'pre-exception output', x//0
Tim Peters8485b562004-08-04 18:46:34 +0000797 ... pre-exception output
798 ... Traceback (most recent call last):
799 ... ZeroDivisionError: integer division or modulo by zero
800 ... '''
801 >>> test = doctest.DocTestFinder().find(f)[0]
802 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000803 ... # doctest: +ELLIPSIS
804 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000805 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000806 Failed example:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000807 print 'pre-exception output', x//0
Edward Loper19b19582004-08-25 23:07:03 +0000808 Exception raised:
809 ...
810 ZeroDivisionError: integer division or modulo by zero
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000811 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000812
813Exception messages may contain newlines:
814
815 >>> def f(x):
816 ... r'''
817 ... >>> raise ValueError, 'multi\nline\nmessage'
818 ... Traceback (most recent call last):
819 ... ValueError: multi
820 ... line
821 ... message
822 ... '''
823 >>> test = doctest.DocTestFinder().find(f)[0]
824 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000825 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000826
827If an exception is expected, but an exception with the wrong type or
828message is raised, then it is reported as a failure:
829
830 >>> def f(x):
831 ... r'''
832 ... >>> raise ValueError, 'message'
833 ... Traceback (most recent call last):
834 ... ValueError: wrong message
835 ... '''
836 >>> test = doctest.DocTestFinder().find(f)[0]
837 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000838 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000839 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000840 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000841 Failed example:
842 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000843 Expected:
844 Traceback (most recent call last):
845 ValueError: wrong message
846 Got:
847 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000848 ...
Tim Peters8485b562004-08-04 18:46:34 +0000849 ValueError: message
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000850 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000851
Tim Peters1fbf9c52004-09-04 17:21:02 +0000852However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
853detail:
854
855 >>> def f(x):
856 ... r'''
857 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
858 ... Traceback (most recent call last):
859 ... ValueError: wrong message
860 ... '''
861 >>> test = doctest.DocTestFinder().find(f)[0]
862 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000863 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000864
865But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
866
867 >>> def f(x):
868 ... r'''
869 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
870 ... Traceback (most recent call last):
871 ... TypeError: wrong type
872 ... '''
873 >>> test = doctest.DocTestFinder().find(f)[0]
874 >>> doctest.DocTestRunner(verbose=False).run(test)
875 ... # doctest: +ELLIPSIS
876 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000877 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000878 Failed example:
879 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
880 Expected:
881 Traceback (most recent call last):
882 TypeError: wrong type
883 Got:
884 Traceback (most recent call last):
885 ...
886 ValueError: message
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000887 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000888
Tim Peters8485b562004-08-04 18:46:34 +0000889If an exception is raised but not expected, then it is reported as an
890unexpected exception:
891
Tim Peters8485b562004-08-04 18:46:34 +0000892 >>> def f(x):
893 ... r'''
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000894 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000895 ... 0
896 ... '''
897 >>> test = doctest.DocTestFinder().find(f)[0]
898 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000899 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000900 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000901 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000902 Failed example:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000903 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000904 Exception raised:
905 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000906 ...
Tim Peters8485b562004-08-04 18:46:34 +0000907 ZeroDivisionError: integer division or modulo by zero
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000908 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000909"""
910 def optionflags(): r"""
911Tests of `DocTestRunner`'s option flag handling.
912
913Several option flags can be used to customize the behavior of the test
914runner. These are defined as module constants in doctest, and passed
Georg Brandlf725b952008-01-05 19:44:22 +0000915to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +0000916together).
917
918The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
919and 1/0:
920
921 >>> def f(x):
922 ... '>>> True\n1\n'
923
924 >>> # Without the flag:
925 >>> test = doctest.DocTestFinder().find(f)[0]
926 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000927 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000928
929 >>> # With the flag:
930 >>> test = doctest.DocTestFinder().find(f)[0]
931 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
932 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000933 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000934 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000935 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000936 Failed example:
937 True
938 Expected:
939 1
940 Got:
941 True
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000942 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000943
944The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
945and the '<BLANKLINE>' marker:
946
947 >>> def f(x):
948 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
949
950 >>> # Without the flag:
951 >>> test = doctest.DocTestFinder().find(f)[0]
952 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000953 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000954
955 >>> # With the flag:
956 >>> test = doctest.DocTestFinder().find(f)[0]
957 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
958 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000959 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000960 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000961 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000962 Failed example:
963 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000964 Expected:
965 a
966 <BLANKLINE>
967 b
968 Got:
969 a
970 <BLANKLINE>
971 b
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000972 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000973
974The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
975treated as equal:
976
977 >>> def f(x):
978 ... '>>> print 1, 2, 3\n 1 2\n 3'
979
980 >>> # Without the flag:
981 >>> test = doctest.DocTestFinder().find(f)[0]
982 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000983 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000984 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000985 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000986 Failed example:
987 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000988 Expected:
989 1 2
990 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000991 Got:
992 1 2 3
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000993 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000994
995 >>> # With the flag:
996 >>> test = doctest.DocTestFinder().find(f)[0]
997 >>> flags = doctest.NORMALIZE_WHITESPACE
998 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000999 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001000
Tim Peters026f8dc2004-08-19 16:38:58 +00001001 An example from the docs:
1002 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
1003 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1004 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1005
Tim Peters8485b562004-08-04 18:46:34 +00001006The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1007output to match any substring in the actual output:
1008
1009 >>> def f(x):
1010 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1011
1012 >>> # Without the flag:
1013 >>> test = doctest.DocTestFinder().find(f)[0]
1014 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001015 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001016 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001017 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001018 Failed example:
1019 print range(15)
1020 Expected:
1021 [0, 1, 2, ..., 14]
1022 Got:
1023 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001024 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001025
1026 >>> # With the flag:
1027 >>> test = doctest.DocTestFinder().find(f)[0]
1028 >>> flags = doctest.ELLIPSIS
1029 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001030 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001031
Tim Peterse594bee2004-08-22 01:47:51 +00001032 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001033
1034 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001035 ... print i**2, #doctest: +ELLIPSIS
1036 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001037
Tim Peters026f8dc2004-08-19 16:38:58 +00001038 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001039
1040 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001041 ... print i,
1042 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001043
Tim Peters026f8dc2004-08-19 16:38:58 +00001044 Examples from the docs:
1045
1046 >>> print range(20) # doctest:+ELLIPSIS
1047 [0, 1, ..., 18, 19]
1048
1049 >>> print range(20) # doctest: +ELLIPSIS
1050 ... # doctest: +NORMALIZE_WHITESPACE
1051 [0, 1, ..., 18, 19]
1052
Tim Peters711bf302006-04-25 03:31:36 +00001053The SKIP flag causes an example to be skipped entirely. I.e., the
1054example is not run. It can be useful in contexts where doctest
1055examples serve as both documentation and test cases, and an example
1056should be included for documentation purposes, but should not be
1057checked (e.g., because its output is random, or depends on resources
1058which would be unavailable.) The SKIP flag can also be used for
1059'commenting out' broken examples.
1060
1061 >>> import unavailable_resource # doctest: +SKIP
1062 >>> unavailable_resource.do_something() # doctest: +SKIP
1063 >>> unavailable_resource.blow_up() # doctest: +SKIP
1064 Traceback (most recent call last):
1065 ...
1066 UncheckedBlowUpError: Nobody checks me.
1067
1068 >>> import random
1069 >>> print random.random() # doctest: +SKIP
1070 0.721216923889
1071
Edward Loper71f55af2004-08-26 01:41:51 +00001072The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001073and actual outputs to be displayed using a unified diff:
1074
1075 >>> def f(x):
1076 ... r'''
1077 ... >>> print '\n'.join('abcdefg')
1078 ... a
1079 ... B
1080 ... c
1081 ... d
1082 ... f
1083 ... g
1084 ... h
1085 ... '''
1086
1087 >>> # Without the flag:
1088 >>> test = doctest.DocTestFinder().find(f)[0]
1089 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001090 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001091 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001092 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001093 Failed example:
1094 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001095 Expected:
1096 a
1097 B
1098 c
1099 d
1100 f
1101 g
1102 h
1103 Got:
1104 a
1105 b
1106 c
1107 d
1108 e
1109 f
1110 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001111 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001112
1113 >>> # With the flag:
1114 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001115 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001116 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001117 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001118 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001119 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001120 Failed example:
1121 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001122 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001123 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001124 a
1125 -B
1126 +b
1127 c
1128 d
1129 +e
1130 f
1131 g
1132 -h
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001133 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001134
Edward Loper71f55af2004-08-26 01:41:51 +00001135The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001136and actual outputs to be displayed using a context diff:
1137
Edward Loper71f55af2004-08-26 01:41:51 +00001138 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001139 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001140 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001141 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001142 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001143 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001144 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001145 Failed example:
1146 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001147 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001148 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001149 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001150 a
1151 ! B
1152 c
1153 d
1154 f
1155 g
1156 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001157 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001158 a
1159 ! b
1160 c
1161 d
1162 + e
1163 f
1164 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001165 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001166
1167
Edward Loper71f55af2004-08-26 01:41:51 +00001168The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001169used by the popular ndiff.py utility. This does intraline difference
1170marking, as well as interline differences.
1171
1172 >>> def f(x):
1173 ... r'''
1174 ... >>> print "a b c d e f g h i j k l m"
1175 ... a b c d e f g h i j k 1 m
1176 ... '''
1177 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001178 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001179 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001180 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001181 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001182 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001183 Failed example:
1184 print "a b c d e f g h i j k l m"
1185 Differences (ndiff with -expected +actual):
1186 - a b c d e f g h i j k 1 m
1187 ? ^
1188 + a b c d e f g h i j k l m
1189 ? + ++ ^
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001190 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001191
1192The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1193failing example:
1194
1195 >>> def f(x):
1196 ... r'''
1197 ... >>> print 1 # first success
1198 ... 1
1199 ... >>> print 2 # first failure
1200 ... 200
1201 ... >>> print 3 # second failure
1202 ... 300
1203 ... >>> print 4 # second success
1204 ... 4
1205 ... >>> print 5 # third failure
1206 ... 500
1207 ... '''
1208 >>> test = doctest.DocTestFinder().find(f)[0]
1209 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1210 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001211 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001212 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001213 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001214 Failed example:
1215 print 2 # first failure
1216 Expected:
1217 200
1218 Got:
1219 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001220 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001221
1222However, output from `report_start` is not supressed:
1223
1224 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001225 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001226 Trying:
1227 print 1 # first success
1228 Expecting:
1229 1
1230 ok
1231 Trying:
1232 print 2 # first failure
1233 Expecting:
1234 200
1235 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001236 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001237 Failed example:
1238 print 2 # first failure
1239 Expected:
1240 200
1241 Got:
1242 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001243 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001244
1245For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1246count as failures:
1247
1248 >>> def f(x):
1249 ... r'''
1250 ... >>> print 1 # first success
1251 ... 1
1252 ... >>> raise ValueError(2) # first failure
1253 ... 200
1254 ... >>> print 3 # second failure
1255 ... 300
1256 ... >>> print 4 # second success
1257 ... 4
1258 ... >>> print 5 # third failure
1259 ... 500
1260 ... '''
1261 >>> test = doctest.DocTestFinder().find(f)[0]
1262 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1263 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1264 ... # doctest: +ELLIPSIS
1265 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001266 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001267 Failed example:
1268 raise ValueError(2) # first failure
1269 Exception raised:
1270 ...
1271 ValueError: 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001272 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001273
Tim Petersad2ef332006-05-10 02:43:01 +00001274New option flags can also be registered, via register_optionflag(). Here
1275we reach into doctest's internals a bit.
1276
1277 >>> unlikely = "UNLIKELY_OPTION_NAME"
1278 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1279 False
1280 >>> new_flag_value = doctest.register_optionflag(unlikely)
1281 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1282 True
1283
1284Before 2.4.4/2.5, registering a name more than once erroneously created
1285more than one flag value. Here we verify that's fixed:
1286
1287 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1288 >>> redundant_flag_value == new_flag_value
1289 True
1290
1291Clean up.
1292 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1293
Tim Petersc6cbab02004-08-22 19:43:28 +00001294 """
1295
Tim Peters8485b562004-08-04 18:46:34 +00001296 def option_directives(): r"""
1297Tests of `DocTestRunner`'s option directive mechanism.
1298
Edward Loper74bca7a2004-08-12 02:27:44 +00001299Option directives can be used to turn option flags on or off for a
1300single example. To turn an option on for an example, follow that
1301example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001302
1303 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001304 ... >>> print range(10) # should fail: no ellipsis
1305 ... [0, 1, ..., 9]
1306 ...
1307 ... >>> print range(10) # doctest: +ELLIPSIS
1308 ... [0, 1, ..., 9]
1309 ... '''
1310 >>> test = doctest.DocTestFinder().find(f)[0]
1311 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001312 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001313 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001314 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001315 Failed example:
1316 print range(10) # should fail: no ellipsis
1317 Expected:
1318 [0, 1, ..., 9]
1319 Got:
1320 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001321 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001322
1323To turn an option off for an example, follow that example with a
1324comment of the form ``# doctest: -OPTION``:
1325
1326 >>> def f(x): r'''
1327 ... >>> print range(10)
1328 ... [0, 1, ..., 9]
1329 ...
1330 ... >>> # should fail: no ellipsis
1331 ... >>> print range(10) # doctest: -ELLIPSIS
1332 ... [0, 1, ..., 9]
1333 ... '''
1334 >>> test = doctest.DocTestFinder().find(f)[0]
1335 >>> doctest.DocTestRunner(verbose=False,
1336 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001337 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001338 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001339 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001340 Failed example:
1341 print range(10) # doctest: -ELLIPSIS
1342 Expected:
1343 [0, 1, ..., 9]
1344 Got:
1345 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001346 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001347
1348Option directives affect only the example that they appear with; they
1349do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001350
Edward Loper74bca7a2004-08-12 02:27:44 +00001351 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001352 ... >>> print range(10) # Should fail: no ellipsis
1353 ... [0, 1, ..., 9]
1354 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001355 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001356 ... [0, 1, ..., 9]
1357 ...
Tim Peters8485b562004-08-04 18:46:34 +00001358 ... >>> print range(10) # Should fail: no ellipsis
1359 ... [0, 1, ..., 9]
1360 ... '''
1361 >>> test = doctest.DocTestFinder().find(f)[0]
1362 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001363 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001364 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001365 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001366 Failed example:
1367 print range(10) # Should fail: no ellipsis
1368 Expected:
1369 [0, 1, ..., 9]
1370 Got:
1371 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001372 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001373 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001374 Failed example:
1375 print range(10) # Should fail: no ellipsis
1376 Expected:
1377 [0, 1, ..., 9]
1378 Got:
1379 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001380 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001381
Edward Loper74bca7a2004-08-12 02:27:44 +00001382Multiple options may be modified by a single option directive. They
1383may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001384
1385 >>> def f(x): r'''
1386 ... >>> print range(10) # Should fail
1387 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001388 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001389 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001390 ... [0, 1, ..., 9]
1391 ... '''
1392 >>> test = doctest.DocTestFinder().find(f)[0]
1393 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001394 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001395 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001396 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001397 Failed example:
1398 print range(10) # Should fail
1399 Expected:
1400 [0, 1, ..., 9]
1401 Got:
1402 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001403 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001404
1405 >>> def f(x): r'''
1406 ... >>> print range(10) # Should fail
1407 ... [0, 1, ..., 9]
1408 ... >>> print range(10) # Should succeed
1409 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1410 ... [0, 1, ..., 9]
1411 ... '''
1412 >>> test = doctest.DocTestFinder().find(f)[0]
1413 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001414 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001415 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001416 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001417 Failed example:
1418 print range(10) # Should fail
1419 Expected:
1420 [0, 1, ..., 9]
1421 Got:
1422 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001423 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001424
1425 >>> def f(x): r'''
1426 ... >>> print range(10) # Should fail
1427 ... [0, 1, ..., 9]
1428 ... >>> print range(10) # Should succeed
1429 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1430 ... [0, 1, ..., 9]
1431 ... '''
1432 >>> test = doctest.DocTestFinder().find(f)[0]
1433 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001434 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001435 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001436 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001437 Failed example:
1438 print range(10) # Should fail
1439 Expected:
1440 [0, 1, ..., 9]
1441 Got:
1442 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001443 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001444
1445The option directive may be put on the line following the source, as
1446long as a continuation prompt is used:
1447
1448 >>> def f(x): r'''
1449 ... >>> print range(10)
1450 ... ... # doctest: +ELLIPSIS
1451 ... [0, 1, ..., 9]
1452 ... '''
1453 >>> test = doctest.DocTestFinder().find(f)[0]
1454 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001455 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001456
Edward Loper74bca7a2004-08-12 02:27:44 +00001457For examples with multi-line source, the option directive may appear
1458at the end of any line:
1459
1460 >>> def f(x): r'''
1461 ... >>> for x in range(10): # doctest: +ELLIPSIS
1462 ... ... print x,
1463 ... 0 1 2 ... 9
1464 ...
1465 ... >>> for x in range(10):
1466 ... ... print x, # doctest: +ELLIPSIS
1467 ... 0 1 2 ... 9
1468 ... '''
1469 >>> test = doctest.DocTestFinder().find(f)[0]
1470 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001471 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001472
1473If more than one line of an example with multi-line source has an
1474option directive, then they are combined:
1475
1476 >>> def f(x): r'''
1477 ... Should fail (option directive not on the last line):
1478 ... >>> for x in range(10): # doctest: +ELLIPSIS
1479 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1480 ... 0 1 2...9
1481 ... '''
1482 >>> test = doctest.DocTestFinder().find(f)[0]
1483 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001484 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001485
1486It is an error to have a comment of the form ``# doctest:`` that is
1487*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1488``OPTION`` is an option that has been registered with
1489`register_option`:
1490
1491 >>> # Error: Option not registered
1492 >>> s = '>>> print 12 #doctest: +BADOPTION'
1493 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1494 Traceback (most recent call last):
1495 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1496
1497 >>> # Error: No + or - prefix
1498 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1499 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1500 Traceback (most recent call last):
1501 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1502
1503It is an error to use an option directive on a line that contains no
1504source:
1505
1506 >>> s = '>>> # doctest: +ELLIPSIS'
1507 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1508 Traceback (most recent call last):
1509 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 +00001510"""
1511
1512def test_testsource(): r"""
1513Unit tests for `testsource()`.
1514
1515The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001516test with that name in that module, and converts it to a script. The
1517example code is converted to regular Python code. The surrounding
1518words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001519
1520 >>> import test.test_doctest
1521 >>> name = 'test.test_doctest.sample_func'
1522 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001523 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001524 #
Tim Peters8485b562004-08-04 18:46:34 +00001525 print sample_func(22)
1526 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001527 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001528 #
Edward Lopera5db6002004-08-12 02:41:30 +00001529 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001530 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001531
1532 >>> name = 'test.test_doctest.SampleNewStyleClass'
1533 >>> print doctest.testsource(test.test_doctest, name)
1534 print '1\n2\n3'
1535 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001536 ## 1
1537 ## 2
1538 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001539 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001540
1541 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1542 >>> print doctest.testsource(test.test_doctest, name)
1543 print SampleClass.a_classmethod(10)
1544 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001545 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001546 print SampleClass(0).a_classmethod(10)
1547 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001548 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001549 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001550"""
1551
1552def test_debug(): r"""
1553
1554Create a docstring that we want to debug:
1555
1556 >>> s = '''
1557 ... >>> x = 12
1558 ... >>> print x
1559 ... 12
1560 ... '''
1561
1562Create some fake stdin input, to feed to the debugger:
1563
1564 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001565 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001566 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001567
1568Run the debugger on the docstring, and then restore sys.stdin.
1569
Edward Loper2de91ba2004-08-27 02:07:46 +00001570 >>> try: doctest.debug_src(s)
1571 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001572 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001573 (Pdb) next
1574 12
Tim Peters8485b562004-08-04 18:46:34 +00001575 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001576 > <string>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001577 (Pdb) print x
1578 12
1579 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001580
1581"""
1582
Jim Fulton356fd192004-08-09 11:34:47 +00001583def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001584 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001585
Tim Peters413ced62004-08-09 15:43:47 +00001586 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001587 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001588 you use it. The doctest module changes sys.stdout so that it can
1589 capture program output. It also temporarily replaces pdb.set_trace
1590 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001591 see debugger output.
1592
1593 >>> doc = '''
1594 ... >>> x = 42
1595 ... >>> import pdb; pdb.set_trace()
1596 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001597 >>> parser = doctest.DocTestParser()
1598 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001599 >>> runner = doctest.DocTestRunner(verbose=False)
1600
1601 To demonstrate this, we'll create a fake standard input that
1602 captures our debugger input:
1603
1604 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001605 >>> real_stdin = sys.stdin
1606 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001607 ... 'print x', # print data defined by the example
1608 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001609 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001610
Edward Loper2de91ba2004-08-27 02:07:46 +00001611 >>> try: runner.run(test)
1612 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001613 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001614 > <doctest foo[1]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001615 -> import pdb; pdb.set_trace()
1616 (Pdb) print x
1617 42
1618 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001619 TestResults(failed=0, attempted=2)
Jim Fulton356fd192004-08-09 11:34:47 +00001620
1621 You can also put pdb.set_trace in a function called from a test:
1622
1623 >>> def calls_set_trace():
1624 ... y=2
1625 ... import pdb; pdb.set_trace()
1626
1627 >>> doc = '''
1628 ... >>> x=1
1629 ... >>> calls_set_trace()
1630 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001631 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001632 >>> real_stdin = sys.stdin
1633 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001634 ... 'print y', # print data defined in the function
1635 ... 'up', # out of function
1636 ... 'print x', # print data defined by the example
1637 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001638 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001639
Tim Peters50c6bdb2004-11-08 22:07:37 +00001640 >>> try:
1641 ... runner.run(test)
1642 ... finally:
1643 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001644 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001645 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1646 -> import pdb; pdb.set_trace()
1647 (Pdb) print y
1648 2
1649 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001650 > <doctest foo[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001651 -> calls_set_trace()
1652 (Pdb) print x
1653 1
1654 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001655 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001656
1657 During interactive debugging, source code is shown, even for
1658 doctest examples:
1659
1660 >>> doc = '''
1661 ... >>> def f(x):
1662 ... ... g(x*2)
1663 ... >>> def g(x):
1664 ... ... print x+3
1665 ... ... import pdb; pdb.set_trace()
1666 ... >>> f(3)
1667 ... '''
1668 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1669 >>> real_stdin = sys.stdin
1670 >>> sys.stdin = _FakeInput([
1671 ... 'list', # list source from example 2
1672 ... 'next', # return from g()
1673 ... 'list', # list source from example 1
1674 ... 'next', # return from f()
1675 ... 'list', # list source from example 3
1676 ... 'continue', # stop debugging
1677 ... ''])
1678 >>> try: runner.run(test)
1679 ... finally: sys.stdin = real_stdin
1680 ... # doctest: +NORMALIZE_WHITESPACE
1681 --Return--
1682 > <doctest foo[1]>(3)g()->None
1683 -> import pdb; pdb.set_trace()
1684 (Pdb) list
1685 1 def g(x):
1686 2 print x+3
1687 3 -> import pdb; pdb.set_trace()
1688 [EOF]
1689 (Pdb) next
1690 --Return--
1691 > <doctest foo[0]>(2)f()->None
1692 -> g(x*2)
1693 (Pdb) list
1694 1 def f(x):
1695 2 -> g(x*2)
1696 [EOF]
1697 (Pdb) next
1698 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001699 > <doctest foo[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001700 -> f(3)
1701 (Pdb) list
1702 1 -> f(3)
1703 [EOF]
1704 (Pdb) continue
1705 **********************************************************************
1706 File "foo.py", line 7, in foo
1707 Failed example:
1708 f(3)
1709 Expected nothing
1710 Got:
1711 9
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001712 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001713 """
1714
Tim Peters50c6bdb2004-11-08 22:07:37 +00001715def test_pdb_set_trace_nested():
1716 """This illustrates more-demanding use of set_trace with nested functions.
1717
1718 >>> class C(object):
1719 ... def calls_set_trace(self):
1720 ... y = 1
1721 ... import pdb; pdb.set_trace()
1722 ... self.f1()
1723 ... y = 2
1724 ... def f1(self):
1725 ... x = 1
1726 ... self.f2()
1727 ... x = 2
1728 ... def f2(self):
1729 ... z = 1
1730 ... z = 2
1731
1732 >>> calls_set_trace = C().calls_set_trace
1733
1734 >>> doc = '''
1735 ... >>> a = 1
1736 ... >>> calls_set_trace()
1737 ... '''
1738 >>> parser = doctest.DocTestParser()
1739 >>> runner = doctest.DocTestRunner(verbose=False)
1740 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1741 >>> real_stdin = sys.stdin
1742 >>> sys.stdin = _FakeInput([
1743 ... 'print y', # print data defined in the function
1744 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z',
1745 ... 'up', 'print x',
1746 ... 'up', 'print y',
1747 ... 'up', 'print foo',
1748 ... 'continue', # stop debugging
1749 ... ''])
1750
1751 >>> try:
1752 ... runner.run(test)
1753 ... finally:
1754 ... sys.stdin = real_stdin
1755 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1756 -> self.f1()
1757 (Pdb) print y
1758 1
1759 (Pdb) step
1760 --Call--
1761 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1762 -> def f1(self):
1763 (Pdb) step
1764 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1765 -> x = 1
1766 (Pdb) step
1767 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1768 -> self.f2()
1769 (Pdb) step
1770 --Call--
1771 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1772 -> def f2(self):
1773 (Pdb) step
1774 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1775 -> z = 1
1776 (Pdb) step
1777 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1778 -> z = 2
1779 (Pdb) print z
1780 1
1781 (Pdb) up
1782 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1783 -> self.f2()
1784 (Pdb) print x
1785 1
1786 (Pdb) up
1787 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1788 -> self.f1()
1789 (Pdb) print y
1790 1
1791 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792 > <doctest foo[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001793 -> calls_set_trace()
1794 (Pdb) print foo
1795 *** NameError: name 'foo' is not defined
1796 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001797 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001798"""
1799
Tim Peters19397e52004-08-06 22:02:59 +00001800def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001801 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001802
1803 We create a Suite by providing a module. A module can be provided
1804 by passing a module object:
1805
1806 >>> import unittest
1807 >>> import test.sample_doctest
1808 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1809 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001810 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001811
1812 We can also supply the module by name:
1813
1814 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1815 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001816 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001817
1818 We can use the current module:
1819
1820 >>> suite = test.sample_doctest.test_suite()
1821 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001822 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001823
1824 We can supply global variables. If we pass globs, they will be
1825 used instead of the module globals. Here we'll pass an empty
1826 globals, triggering an extra error:
1827
1828 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1829 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001830 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001831
1832 Alternatively, we can provide extra globals. Here we'll make an
1833 error go away by providing an extra global variable:
1834
1835 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1836 ... extraglobs={'y': 1})
1837 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001838 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001839
1840 You can pass option flags. Here we'll cause an extra error
1841 by disabling the blank-line feature:
1842
1843 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001844 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001845 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001846 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001847
Tim Peters1e277ee2004-08-07 05:37:52 +00001848 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001849
Jim Fultonf54bad42004-08-28 14:57:56 +00001850 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001851 ... import test.test_doctest
1852 ... test.test_doctest.sillySetup = True
1853
Jim Fultonf54bad42004-08-28 14:57:56 +00001854 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001855 ... import test.test_doctest
1856 ... del test.test_doctest.sillySetup
1857
1858 Here, we installed a silly variable that the test expects:
1859
1860 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1861 ... setUp=setUp, tearDown=tearDown)
1862 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001863 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001864
1865 But the tearDown restores sanity:
1866
1867 >>> import test.test_doctest
1868 >>> test.test_doctest.sillySetup
1869 Traceback (most recent call last):
1870 ...
1871 AttributeError: 'module' object has no attribute 'sillySetup'
1872
Jim Fultonf54bad42004-08-28 14:57:56 +00001873 The setUp and tearDown funtions are passed test objects. Here
1874 we'll use the setUp function to supply the missing variable y:
1875
1876 >>> def setUp(test):
1877 ... test.globs['y'] = 1
1878
1879 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1880 >>> suite.run(unittest.TestResult())
1881 <unittest.TestResult run=9 errors=0 failures=3>
1882
1883 Here, we didn't need to use a tearDown function because we
1884 modified the test globals, which are a copy of the
1885 sample_doctest module dictionary. The test globals are
1886 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001887 """
1888
1889def test_DocFileSuite():
1890 """We can test tests found in text files using a DocFileSuite.
1891
1892 We create a suite by providing the names of one or more text
1893 files that include examples:
1894
1895 >>> import unittest
1896 >>> suite = doctest.DocFileSuite('test_doctest.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00001897 ... 'test_doctest2.txt',
1898 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00001899 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00001900 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001901
1902 The test files are looked for in the directory containing the
1903 calling module. A package keyword argument can be provided to
1904 specify a different relative location.
1905
1906 >>> import unittest
1907 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1908 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00001909 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001910 ... package='test')
1911 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00001912 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001913
Brett Cannon43e53f82007-11-21 00:47:36 +00001914 Support for using a package's __loader__.get_data() is also
1915 provided.
1916
1917 >>> import unittest, pkgutil, test
Brett Cannoneaa2c982007-11-23 00:06:51 +00001918 >>> added_loader = False
Brett Cannon43e53f82007-11-21 00:47:36 +00001919 >>> if not hasattr(test, '__loader__'):
1920 ... test.__loader__ = pkgutil.get_loader(test)
1921 ... added_loader = True
1922 >>> try:
1923 ... suite = doctest.DocFileSuite('test_doctest.txt',
1924 ... 'test_doctest2.txt',
1925 ... 'test_doctest4.txt',
1926 ... package='test')
1927 ... suite.run(unittest.TestResult())
1928 ... finally:
Brett Cannon9db1d5a2007-11-21 00:58:03 +00001929 ... if added_loader:
1930 ... del test.__loader__
Brett Cannon43e53f82007-11-21 00:47:36 +00001931 <unittest.TestResult run=3 errors=0 failures=3>
1932
Edward Loper0273f5b2004-09-18 20:27:04 +00001933 '/' should be used as a path separator. It will be converted
1934 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001935
1936 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1937 >>> suite.run(unittest.TestResult())
1938 <unittest.TestResult run=1 errors=0 failures=1>
1939
Edward Loper0273f5b2004-09-18 20:27:04 +00001940 If DocFileSuite is used from an interactive session, then files
1941 are resolved relative to the directory of sys.argv[0]:
1942
Christian Heimesc756d002007-11-27 21:34:01 +00001943 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00001944 >>> save_argv = sys.argv
1945 >>> sys.argv = [test.test_doctest.__file__]
1946 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimesc756d002007-11-27 21:34:01 +00001947 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00001948 >>> sys.argv = save_argv
1949
Edward Loper052d0cd2004-09-19 17:19:33 +00001950 By setting `module_relative=False`, os-specific paths may be
1951 used (including absolute paths and paths relative to the
1952 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00001953
1954 >>> # Get the absolute path of the test package.
1955 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
1956 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
1957
1958 >>> # Use it to find the absolute path of test_doctest.txt.
1959 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
1960
Edward Loper052d0cd2004-09-19 17:19:33 +00001961 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00001962 >>> suite.run(unittest.TestResult())
1963 <unittest.TestResult run=1 errors=0 failures=1>
1964
Edward Loper052d0cd2004-09-19 17:19:33 +00001965 It is an error to specify `package` when `module_relative=False`:
1966
1967 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
1968 ... package='test')
1969 Traceback (most recent call last):
1970 ValueError: Package may only be specified for module-relative paths.
1971
Tim Peters19397e52004-08-06 22:02:59 +00001972 You can specify initial global variables:
1973
1974 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1975 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00001976 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001977 ... globs={'favorite_color': 'blue'})
1978 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00001979 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001980
1981 In this case, we supplied a missing favorite color. You can
1982 provide doctest options:
1983
1984 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1985 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00001986 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001987 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1988 ... globs={'favorite_color': 'blue'})
1989 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00001990 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001991
1992 And, you can provide setUp and tearDown functions:
1993
Jim Fultonf54bad42004-08-28 14:57:56 +00001994 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001995 ... import test.test_doctest
1996 ... test.test_doctest.sillySetup = True
1997
Jim Fultonf54bad42004-08-28 14:57:56 +00001998 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001999 ... import test.test_doctest
2000 ... del test.test_doctest.sillySetup
2001
2002 Here, we installed a silly variable that the test expects:
2003
2004 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2005 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002006 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002007 ... setUp=setUp, tearDown=tearDown)
2008 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00002009 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002010
2011 But the tearDown restores sanity:
2012
2013 >>> import test.test_doctest
2014 >>> test.test_doctest.sillySetup
2015 Traceback (most recent call last):
2016 ...
2017 AttributeError: 'module' object has no attribute 'sillySetup'
2018
Jim Fultonf54bad42004-08-28 14:57:56 +00002019 The setUp and tearDown funtions are passed test objects.
2020 Here, we'll use a setUp function to set the favorite color in
2021 test_doctest.txt:
2022
2023 >>> def setUp(test):
2024 ... test.globs['favorite_color'] = 'blue'
2025
2026 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2027 >>> suite.run(unittest.TestResult())
2028 <unittest.TestResult run=1 errors=0 failures=0>
2029
2030 Here, we didn't need to use a tearDown function because we
2031 modified the test globals. The test globals are
2032 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002033
Fred Drake7c404a42004-12-21 23:46:34 +00002034 Tests in a file run using `DocFileSuite` can also access the
2035 `__file__` global, which is set to the name of the file
2036 containing the tests:
2037
2038 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2039 >>> suite.run(unittest.TestResult())
2040 <unittest.TestResult run=1 errors=0 failures=0>
2041
George Yoshidaf3c65de2006-05-28 16:39:09 +00002042 If the tests contain non-ASCII characters, we have to specify which
2043 encoding the file is encoded with. We do so by using the `encoding`
2044 parameter:
2045
2046 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2047 ... 'test_doctest2.txt',
2048 ... 'test_doctest4.txt',
2049 ... encoding='utf-8')
2050 >>> suite.run(unittest.TestResult())
2051 <unittest.TestResult run=3 errors=0 failures=2>
2052
Jim Fultonf54bad42004-08-28 14:57:56 +00002053 """
Tim Peters19397e52004-08-06 22:02:59 +00002054
Jim Fulton07a349c2004-08-22 14:10:00 +00002055def test_trailing_space_in_test():
2056 """
Tim Petersa7def722004-08-23 22:13:22 +00002057 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002058
Jim Fulton07a349c2004-08-22 14:10:00 +00002059 >>> x, y = 'foo', ''
2060 >>> print x, y
2061 foo \n
2062 """
Tim Peters19397e52004-08-06 22:02:59 +00002063
Jim Fultonf54bad42004-08-28 14:57:56 +00002064
2065def test_unittest_reportflags():
2066 """Default unittest reporting flags can be set to control reporting
2067
2068 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2069 only the first failure of each test. First, we'll look at the
2070 output without the flag. The file test_doctest.txt file has two
2071 tests. They both fail if blank lines are disabled:
2072
2073 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2074 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2075 >>> import unittest
2076 >>> result = suite.run(unittest.TestResult())
2077 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2078 Traceback ...
2079 Failed example:
2080 favorite_color
2081 ...
2082 Failed example:
2083 if 1:
2084 ...
2085
2086 Note that we see both failures displayed.
2087
2088 >>> old = doctest.set_unittest_reportflags(
2089 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2090
2091 Now, when we run the test:
2092
2093 >>> result = suite.run(unittest.TestResult())
2094 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2095 Traceback ...
2096 Failed example:
2097 favorite_color
2098 Exception raised:
2099 ...
2100 NameError: name 'favorite_color' is not defined
2101 <BLANKLINE>
2102 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002103
Jim Fultonf54bad42004-08-28 14:57:56 +00002104 We get only the first failure.
2105
2106 If we give any reporting options when we set up the tests,
2107 however:
2108
2109 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2110 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2111
2112 Then the default eporting options are ignored:
2113
2114 >>> result = suite.run(unittest.TestResult())
2115 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2116 Traceback ...
2117 Failed example:
2118 favorite_color
2119 ...
2120 Failed example:
2121 if 1:
2122 print 'a'
2123 print
2124 print 'b'
2125 Differences (ndiff with -expected +actual):
2126 a
2127 - <BLANKLINE>
2128 +
2129 b
2130 <BLANKLINE>
2131 <BLANKLINE>
2132
2133
2134 Test runners can restore the formatting flags after they run:
2135
2136 >>> ignored = doctest.set_unittest_reportflags(old)
2137
2138 """
2139
Edward Loper052d0cd2004-09-19 17:19:33 +00002140def test_testfile(): r"""
2141Tests for the `testfile()` function. This function runs all the
2142doctest examples in a given file. In its simple invokation, it is
2143called with the name of a file, which is taken to be relative to the
2144calling module. The return value is (#failures, #tests).
2145
2146 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2147 **********************************************************************
2148 File "...", line 6, in test_doctest.txt
2149 Failed example:
2150 favorite_color
2151 Exception raised:
2152 ...
2153 NameError: name 'favorite_color' is not defined
2154 **********************************************************************
2155 1 items had failures:
2156 1 of 2 in test_doctest.txt
2157 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002158 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002159 >>> doctest.master = None # Reset master.
2160
2161(Note: we'll be clearing doctest.master after each call to
2162`doctest.testfile`, to supress warnings about multiple tests with the
2163same name.)
2164
2165Globals may be specified with the `globs` and `extraglobs` parameters:
2166
2167 >>> globs = {'favorite_color': 'blue'}
2168 >>> doctest.testfile('test_doctest.txt', globs=globs)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002169 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002170 >>> doctest.master = None # Reset master.
2171
2172 >>> extraglobs = {'favorite_color': 'red'}
2173 >>> doctest.testfile('test_doctest.txt', globs=globs,
2174 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2175 **********************************************************************
2176 File "...", line 6, in test_doctest.txt
2177 Failed example:
2178 favorite_color
2179 Expected:
2180 'blue'
2181 Got:
2182 'red'
2183 **********************************************************************
2184 1 items had failures:
2185 1 of 2 in test_doctest.txt
2186 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002187 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002188 >>> doctest.master = None # Reset master.
2189
2190The file may be made relative to a given module or package, using the
2191optional `module_relative` parameter:
2192
2193 >>> doctest.testfile('test_doctest.txt', globs=globs,
2194 ... module_relative='test')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002195 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002196 >>> doctest.master = None # Reset master.
2197
2198Verbosity can be increased with the optional `verbose` paremter:
2199
2200 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2201 Trying:
2202 favorite_color
2203 Expecting:
2204 'blue'
2205 ok
2206 Trying:
2207 if 1:
2208 print 'a'
2209 print
2210 print 'b'
2211 Expecting:
2212 a
2213 <BLANKLINE>
2214 b
2215 ok
2216 1 items passed all tests:
2217 2 tests in test_doctest.txt
2218 2 tests in 1 items.
2219 2 passed and 0 failed.
2220 Test passed.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002221 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002222 >>> doctest.master = None # Reset master.
2223
2224The name of the test may be specified with the optional `name`
2225parameter:
2226
2227 >>> doctest.testfile('test_doctest.txt', name='newname')
2228 ... # doctest: +ELLIPSIS
2229 **********************************************************************
2230 File "...", line 6, in newname
2231 ...
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002232 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002233 >>> doctest.master = None # Reset master.
2234
2235The summary report may be supressed with the optional `report`
2236parameter:
2237
2238 >>> doctest.testfile('test_doctest.txt', report=False)
2239 ... # doctest: +ELLIPSIS
2240 **********************************************************************
2241 File "...", line 6, in test_doctest.txt
2242 Failed example:
2243 favorite_color
2244 Exception raised:
2245 ...
2246 NameError: name 'favorite_color' is not defined
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002247 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002248 >>> doctest.master = None # Reset master.
2249
2250The optional keyword argument `raise_on_error` can be used to raise an
2251exception on the first error (which may be useful for postmortem
2252debugging):
2253
2254 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2255 ... # doctest: +ELLIPSIS
2256 Traceback (most recent call last):
2257 UnexpectedException: ...
2258 >>> doctest.master = None # Reset master.
George Yoshidaf3c65de2006-05-28 16:39:09 +00002259
2260If the tests contain non-ASCII characters, the tests might fail, since
2261it's unknown which encoding is used. The encoding can be specified
2262using the optional keyword argument `encoding`:
2263
2264 >>> doctest.testfile('test_doctest4.txt') # doctest: +ELLIPSIS
2265 **********************************************************************
2266 File "...", line 7, in test_doctest4.txt
2267 Failed example:
2268 u'...'
2269 Expected:
2270 u'f\xf6\xf6'
2271 Got:
2272 u'f\xc3\xb6\xc3\xb6'
2273 **********************************************************************
2274 ...
2275 **********************************************************************
2276 1 items had failures:
2277 2 of 4 in test_doctest4.txt
2278 ***Test Failed*** 2 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002279 TestResults(failed=2, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002280 >>> doctest.master = None # Reset master.
2281
2282 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002283 TestResults(failed=0, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002284 >>> doctest.master = None # Reset master.
Edward Loper052d0cd2004-09-19 17:19:33 +00002285"""
2286
Tim Petersa7def722004-08-23 22:13:22 +00002287# old_test1, ... used to live in doctest.py, but cluttered it. Note
2288# that these use the deprecated doctest.Tester, so should go away (or
2289# be rewritten) someday.
2290
2291# Ignore all warnings about the use of class Tester in this module.
2292# Note that the name of this module may differ depending on how it's
2293# imported, so the use of __name__ is important.
2294warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2295 __name__, 0)
2296
2297def old_test1(): r"""
2298>>> from doctest import Tester
2299>>> t = Tester(globs={'x': 42}, verbose=0)
2300>>> t.runstring(r'''
2301... >>> x = x * 2
2302... >>> print x
2303... 42
2304... ''', 'XYZ')
2305**********************************************************************
2306Line 3, in XYZ
2307Failed example:
2308 print x
2309Expected:
2310 42
2311Got:
2312 84
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002313TestResults(failed=1, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002314>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002315TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002316>>> t.summarize()
2317**********************************************************************
23181 items had failures:
2319 1 of 2 in XYZ
2320***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002321TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002322>>> t.summarize(verbose=1)
23231 items passed all tests:
2324 2 tests in example2
2325**********************************************************************
23261 items had failures:
2327 1 of 2 in XYZ
23284 tests in 2 items.
23293 passed and 1 failed.
2330***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002331TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002332"""
2333
2334def old_test2(): r"""
2335 >>> from doctest import Tester
2336 >>> t = Tester(globs={}, verbose=1)
2337 >>> test = r'''
2338 ... # just an example
2339 ... >>> x = 1 + 2
2340 ... >>> x
2341 ... 3
2342 ... '''
2343 >>> t.runstring(test, "Example")
2344 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002345 Trying:
2346 x = 1 + 2
2347 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002348 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002349 Trying:
2350 x
2351 Expecting:
2352 3
Tim Petersa7def722004-08-23 22:13:22 +00002353 ok
2354 0 of 2 examples failed in string Example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002355 TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002356"""
2357
2358def old_test3(): r"""
2359 >>> from doctest import Tester
2360 >>> t = Tester(globs={}, verbose=0)
2361 >>> def _f():
2362 ... '''Trivial docstring example.
2363 ... >>> assert 2 == 2
2364 ... '''
2365 ... return 32
2366 ...
2367 >>> t.rundoc(_f) # expect 0 failures in 1 example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002368 TestResults(failed=0, attempted=1)
Tim Petersa7def722004-08-23 22:13:22 +00002369"""
2370
2371def old_test4(): """
Christian Heimesc756d002007-11-27 21:34:01 +00002372 >>> import types
2373 >>> m1 = types.ModuleType('_m1')
2374 >>> m2 = types.ModuleType('_m2')
Tim Petersa7def722004-08-23 22:13:22 +00002375 >>> test_data = \"""
2376 ... def _f():
2377 ... '''>>> assert 1 == 1
2378 ... '''
2379 ... def g():
2380 ... '''>>> assert 2 != 1
2381 ... '''
2382 ... class H:
2383 ... '''>>> assert 2 > 1
2384 ... '''
2385 ... def bar(self):
2386 ... '''>>> assert 1 < 2
2387 ... '''
2388 ... \"""
2389 >>> exec test_data in m1.__dict__
2390 >>> exec test_data in m2.__dict__
2391 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2392
2393 Tests that objects outside m1 are excluded:
2394
2395 >>> from doctest import Tester
2396 >>> t = Tester(globs={}, verbose=0)
2397 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002398 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002399
2400 Once more, not excluding stuff outside m1:
2401
2402 >>> t = Tester(globs={}, verbose=0)
2403 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002404 TestResults(failed=0, attempted=8)
Tim Petersa7def722004-08-23 22:13:22 +00002405
2406 The exclusion of objects from outside the designated module is
2407 meant to be invoked automagically by testmod.
2408
2409 >>> doctest.testmod(m1, verbose=False)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002410 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002411"""
2412
Tim Peters8485b562004-08-04 18:46:34 +00002413######################################################################
2414## Main
2415######################################################################
2416
2417def test_main():
2418 # Check the doctest cases in doctest itself:
2419 test_support.run_doctest(doctest, verbosity=True)
2420 # Check the doctest cases defined here:
2421 from test import test_doctest
2422 test_support.run_doctest(test_doctest, verbosity=True)
2423
Christian Heimesc5f05e42008-02-23 17:40:11 +00002424import trace, sys
Tim Peters8485b562004-08-04 18:46:34 +00002425def test_coverage(coverdir):
2426 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2427 trace=0, count=1)
2428 tracer.run('reload(doctest); test_main()')
2429 r = tracer.results()
2430 print 'Writing coverage results...'
2431 r.write_results(show_missing=True, summary=True,
2432 coverdir=coverdir)
2433
2434if __name__ == '__main__':
2435 if '-c' in sys.argv:
2436 test_coverage('/tmp/doctest.cover')
2437 else:
2438 test_main()