blob: ac9d00d6ae80e87fd6fe9ac59b995ff35e7e1174 [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Barry Warsaw04f357c2002-07-23 19:04:11 +00005from test import test_support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Tim Petersa7def722004-08-23 22:13:22 +00007import warnings
Tim Peters8485b562004-08-04 18:46:34 +00008
9######################################################################
10## Sample Objects (used by test cases)
11######################################################################
12
13def sample_func(v):
14 """
Tim Peters19397e52004-08-06 22:02:59 +000015 Blah blah
16
Tim Peters8485b562004-08-04 18:46:34 +000017 >>> print sample_func(22)
18 44
Tim Peters19397e52004-08-06 22:02:59 +000019
20 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000021 """
22 return v+v
23
24class SampleClass:
25 """
26 >>> print 1
27 1
Edward Loper4ae900f2004-09-21 03:20:34 +000028
29 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
30 >>>
31 ...
32
33 Multiline example:
34 >>> sc = SampleClass(3)
35 >>> for i in range(10):
36 ... sc = sc.double()
37 ... print sc.get(),
38 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000039 """
40 def __init__(self, val):
41 """
42 >>> print SampleClass(12).get()
43 12
44 """
45 self.val = val
46
47 def double(self):
48 """
49 >>> print SampleClass(12).double().get()
50 24
51 """
52 return SampleClass(self.val + self.val)
53
54 def get(self):
55 """
56 >>> print SampleClass(-5).get()
57 -5
58 """
59 return self.val
60
61 def a_staticmethod(v):
62 """
63 >>> print SampleClass.a_staticmethod(10)
64 11
65 """
66 return v+1
67 a_staticmethod = staticmethod(a_staticmethod)
68
69 def a_classmethod(cls, v):
70 """
71 >>> print SampleClass.a_classmethod(10)
72 12
73 >>> print SampleClass(0).a_classmethod(10)
74 12
75 """
76 return v+2
77 a_classmethod = classmethod(a_classmethod)
78
79 a_property = property(get, doc="""
80 >>> print SampleClass(22).a_property
81 22
82 """)
83
84 class NestedClass:
85 """
86 >>> x = SampleClass.NestedClass(5)
87 >>> y = x.square()
88 >>> print y.get()
89 25
90 """
91 def __init__(self, val=0):
92 """
93 >>> print SampleClass.NestedClass().get()
94 0
95 """
96 self.val = val
97 def square(self):
98 return SampleClass.NestedClass(self.val*self.val)
99 def get(self):
100 return self.val
101
102class SampleNewStyleClass(object):
103 r"""
104 >>> print '1\n2\n3'
105 1
106 2
107 3
108 """
109 def __init__(self, val):
110 """
111 >>> print SampleNewStyleClass(12).get()
112 12
113 """
114 self.val = val
115
116 def double(self):
117 """
118 >>> print SampleNewStyleClass(12).double().get()
119 24
120 """
121 return SampleNewStyleClass(self.val + self.val)
122
123 def get(self):
124 """
125 >>> print SampleNewStyleClass(-5).get()
126 -5
127 """
128 return self.val
129
130######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000131## Fake stdin (for testing interactive debugging)
132######################################################################
133
134class _FakeInput:
135 """
136 A fake input stream for pdb's interactive debugger. Whenever a
137 line is read, print it (to simulate the user typing it), and then
138 return it. The set of lines to return is specified in the
139 constructor; they should not have trailing newlines.
140 """
141 def __init__(self, lines):
142 self.lines = lines
143
144 def readline(self):
145 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000146 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000147 return line+'\n'
148
149######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000150## Test Cases
151######################################################################
152
153def test_Example(): r"""
154Unit tests for the `Example` class.
155
Edward Lopera6b68322004-08-26 00:05:43 +0000156Example is a simple container class that holds:
157 - `source`: A source string.
158 - `want`: An expected output string.
159 - `exc_msg`: An expected exception message string (or None if no
160 exception is expected).
161 - `lineno`: A line number (within the docstring).
162 - `indent`: The example's indentation in the input string.
163 - `options`: An option dictionary, mapping option flags to True or
164 False.
Tim Peters8485b562004-08-04 18:46:34 +0000165
Edward Lopera6b68322004-08-26 00:05:43 +0000166These attributes are set by the constructor. `source` and `want` are
167required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000168
Edward Lopera6b68322004-08-26 00:05:43 +0000169 >>> example = doctest.Example('print 1', '1\n')
170 >>> (example.source, example.want, example.exc_msg,
171 ... example.lineno, example.indent, example.options)
172 ('print 1\n', '1\n', None, 0, 0, {})
173
174The first three attributes (`source`, `want`, and `exc_msg`) may be
175specified positionally; the remaining arguments should be specified as
176keyword arguments:
177
178 >>> exc_msg = 'IndexError: pop from an empty list'
179 >>> example = doctest.Example('[].pop()', '', exc_msg,
180 ... lineno=5, indent=4,
181 ... options={doctest.ELLIPSIS: True})
182 >>> (example.source, example.want, example.exc_msg,
183 ... example.lineno, example.indent, example.options)
184 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
185
186The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000187
Tim Petersbb431472004-08-09 03:51:46 +0000188 Source spans a single line: no terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000189 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000190 >>> e.source, e.want
191 ('print 1\n', '1\n')
192
Edward Lopera6b68322004-08-26 00:05:43 +0000193 >>> e = doctest.Example('print 1\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000194 >>> e.source, e.want
195 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000196
Tim Petersbb431472004-08-09 03:51:46 +0000197 Source spans multiple lines: require terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000198 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000199 >>> e.source, e.want
200 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000201
Edward Lopera6b68322004-08-26 00:05:43 +0000202 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000203 >>> e.source, e.want
204 ('print 1;\nprint 2\n', '1\n2\n')
205
Edward Lopera6b68322004-08-26 00:05:43 +0000206 Empty source string (which should never appear in real examples)
207 >>> e = doctest.Example('', '')
208 >>> e.source, e.want
209 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000210
Edward Lopera6b68322004-08-26 00:05:43 +0000211The constructor normalizes the `want` string to end in a newline,
212unless it's the empty string:
213
214 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000215 >>> e.source, e.want
216 ('print 1\n', '1\n')
217
Edward Lopera6b68322004-08-26 00:05:43 +0000218 >>> e = doctest.Example('print 1', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000219 >>> e.source, e.want
220 ('print 1\n', '1\n')
221
Edward Lopera6b68322004-08-26 00:05:43 +0000222 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000223 >>> e.source, e.want
224 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000225
226The constructor normalizes the `exc_msg` string to end in a newline,
227unless it's `None`:
228
229 Message spans one line
230 >>> exc_msg = 'IndexError: pop from an empty list'
231 >>> e = doctest.Example('[].pop()', '', exc_msg)
232 >>> e.exc_msg
233 'IndexError: pop from an empty list\n'
234
235 >>> exc_msg = 'IndexError: pop from an empty list\n'
236 >>> e = doctest.Example('[].pop()', '', exc_msg)
237 >>> e.exc_msg
238 'IndexError: pop from an empty list\n'
239
240 Message spans multiple lines
241 >>> exc_msg = 'ValueError: 1\n 2'
242 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
243 >>> e.exc_msg
244 'ValueError: 1\n 2\n'
245
246 >>> exc_msg = 'ValueError: 1\n 2\n'
247 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
248 >>> e.exc_msg
249 'ValueError: 1\n 2\n'
250
251 Empty (but non-None) exception message (which should never appear
252 in real examples)
253 >>> exc_msg = ''
254 >>> e = doctest.Example('raise X()', '', exc_msg)
255 >>> e.exc_msg
256 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000257"""
258
259def test_DocTest(): r"""
260Unit tests for the `DocTest` class.
261
262DocTest is a collection of examples, extracted from a docstring, along
263with information about where the docstring comes from (a name,
264filename, and line number). The docstring is parsed by the `DocTest`
265constructor:
266
267 >>> docstring = '''
268 ... >>> print 12
269 ... 12
270 ...
271 ... Non-example text.
272 ...
273 ... >>> print 'another\example'
274 ... another
275 ... example
276 ... '''
277 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000278 >>> parser = doctest.DocTestParser()
279 >>> test = parser.get_doctest(docstring, globs, 'some_test',
280 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000281 >>> print test
282 <DocTest some_test from some_file:20 (2 examples)>
283 >>> len(test.examples)
284 2
285 >>> e1, e2 = test.examples
286 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000287 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000288 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000289 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000290
291Source information (name, filename, and line number) is available as
292attributes on the doctest object:
293
294 >>> (test.name, test.filename, test.lineno)
295 ('some_test', 'some_file', 20)
296
297The line number of an example within its containing file is found by
298adding the line number of the example and the line number of its
299containing test:
300
301 >>> test.lineno + e1.lineno
302 21
303 >>> test.lineno + e2.lineno
304 26
305
306If the docstring contains inconsistant leading whitespace in the
307expected output of an example, then `DocTest` will raise a ValueError:
308
309 >>> docstring = r'''
310 ... >>> print 'bad\nindentation'
311 ... bad
312 ... indentation
313 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000314 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000315 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000316 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000317
318If the docstring contains inconsistent leading whitespace on
319continuation lines, then `DocTest` will raise a ValueError:
320
321 >>> docstring = r'''
322 ... >>> print ('bad indentation',
323 ... ... 2)
324 ... ('bad', 'indentation')
325 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000326 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000327 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000328 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
Tim Peters8485b562004-08-04 18:46:34 +0000329
330If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
331will raise a ValueError:
332
333 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000334 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000335 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000336 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
337
338If there's no blank space after a PS2 prompt ('...'), then `DocTest`
339will raise a ValueError:
340
341 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000342 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000343 Traceback (most recent call last):
344 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
345
Tim Peters8485b562004-08-04 18:46:34 +0000346"""
347
Tim Peters8485b562004-08-04 18:46:34 +0000348def test_DocTestFinder(): r"""
349Unit tests for the `DocTestFinder` class.
350
351DocTestFinder is used to extract DocTests from an object's docstring
352and the docstrings of its contained objects. It can be used with
353modules, functions, classes, methods, staticmethods, classmethods, and
354properties.
355
356Finding Tests in Functions
357~~~~~~~~~~~~~~~~~~~~~~~~~~
358For a function whose docstring contains examples, DocTestFinder.find()
359will return a single test (for that function's docstring):
360
Tim Peters8485b562004-08-04 18:46:34 +0000361 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000362
363We'll simulate a __file__ attr that ends in pyc:
364
365 >>> import test.test_doctest
366 >>> old = test.test_doctest.__file__
367 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
368
Tim Peters8485b562004-08-04 18:46:34 +0000369 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000370
Edward Loper74bca7a2004-08-12 02:27:44 +0000371 >>> print tests # doctest: +ELLIPSIS
Tim Petersa7def722004-08-23 22:13:22 +0000372 [<DocTest sample_func from ...:13 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000373
Tim Peters4de7c5c2004-08-23 22:38:05 +0000374The exact name depends on how test_doctest was invoked, so allow for
375leading path components.
376
377 >>> tests[0].filename # doctest: +ELLIPSIS
378 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000379
380 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000381
Jim Fulton07a349c2004-08-22 14:10:00 +0000382
Tim Peters8485b562004-08-04 18:46:34 +0000383 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000384 >>> (e.source, e.want, e.lineno)
385 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000386
Edward Loper32ddbf72004-09-13 05:47:24 +0000387By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000388
389 >>> def no_docstring(v):
390 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000391 >>> finder.find(no_docstring)
392 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000393
394However, the optional argument `exclude_empty` to the DocTestFinder
395constructor can be used to exclude tests for objects with empty
396docstrings:
397
398 >>> def no_docstring(v):
399 ... pass
400 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
401 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000402 []
403
404If the function has a docstring with no examples, then a test with no
405examples is returned. (This lets `DocTestRunner` collect statistics
406about which functions have no tests -- but is that useful? And should
407an empty test also be created when there's no docstring?)
408
409 >>> def no_examples(v):
410 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000411 >>> finder.find(no_examples) # doctest: +ELLIPSIS
412 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000413
414Finding Tests in Classes
415~~~~~~~~~~~~~~~~~~~~~~~~
416For a class, DocTestFinder will create a test for the class's
417docstring, and will recursively explore its contents, including
418methods, classmethods, staticmethods, properties, and nested classes.
419
420 >>> finder = doctest.DocTestFinder()
421 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000422 >>> for t in tests:
423 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000424 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000425 3 SampleClass.NestedClass
426 1 SampleClass.NestedClass.__init__
427 1 SampleClass.__init__
428 2 SampleClass.a_classmethod
429 1 SampleClass.a_property
430 1 SampleClass.a_staticmethod
431 1 SampleClass.double
432 1 SampleClass.get
433
434New-style classes are also supported:
435
436 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000437 >>> for t in tests:
438 ... print '%2s %s' % (len(t.examples), t.name)
439 1 SampleNewStyleClass
440 1 SampleNewStyleClass.__init__
441 1 SampleNewStyleClass.double
442 1 SampleNewStyleClass.get
443
444Finding Tests in Modules
445~~~~~~~~~~~~~~~~~~~~~~~~
446For a module, DocTestFinder will create a test for the class's
447docstring, and will recursively explore its contents, including
448functions, classes, and the `__test__` dictionary, if it exists:
449
450 >>> # A module
451 >>> import new
452 >>> m = new.module('some_module')
453 >>> def triple(val):
454 ... '''
Edward Loper4ae900f2004-09-21 03:20:34 +0000455 ... >>> print triple(11)
Tim Peters8485b562004-08-04 18:46:34 +0000456 ... 33
457 ... '''
458 ... return val*3
459 >>> m.__dict__.update({
460 ... 'sample_func': sample_func,
461 ... 'SampleClass': SampleClass,
462 ... '__doc__': '''
463 ... Module docstring.
464 ... >>> print 'module'
465 ... module
466 ... ''',
467 ... '__test__': {
468 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
469 ... 'c': triple}})
470
471 >>> finder = doctest.DocTestFinder()
472 >>> # Use module=test.test_doctest, to prevent doctest from
473 >>> # ignoring the objects since they weren't defined in m.
474 >>> import test.test_doctest
475 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000476 >>> for t in tests:
477 ... print '%2s %s' % (len(t.examples), t.name)
478 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000479 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000480 3 some_module.SampleClass.NestedClass
481 1 some_module.SampleClass.NestedClass.__init__
482 1 some_module.SampleClass.__init__
483 2 some_module.SampleClass.a_classmethod
484 1 some_module.SampleClass.a_property
485 1 some_module.SampleClass.a_staticmethod
486 1 some_module.SampleClass.double
487 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000488 1 some_module.__test__.c
489 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000490 1 some_module.sample_func
491
492Duplicate Removal
493~~~~~~~~~~~~~~~~~
494If a single object is listed twice (under different names), then tests
495will only be generated for it once:
496
Tim Petersf3f57472004-08-08 06:11:48 +0000497 >>> from test import doctest_aliases
Edward Loper32ddbf72004-09-13 05:47:24 +0000498 >>> tests = excl_empty_finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000499 >>> print len(tests)
500 2
501 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000502 test.doctest_aliases.TwoNames
503
504 TwoNames.f and TwoNames.g are bound to the same object.
505 We can't guess which will be found in doctest's traversal of
506 TwoNames.__dict__ first, so we have to allow for either.
507
508 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000509 True
510
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000511Empty Tests
512~~~~~~~~~~~
513By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000514
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000515 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000516 >>> for t in tests:
517 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000518 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000519 3 SampleClass.NestedClass
520 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000521 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000522 2 SampleClass.a_classmethod
523 1 SampleClass.a_property
524 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000525 1 SampleClass.double
526 1 SampleClass.get
527
528By default, that excluded objects with no doctests. exclude_empty=False
529tells it to include (empty) tests for objects with no doctests. This feature
530is really to support backward compatibility in what doctest.master.summarize()
531displays.
532
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000533 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000534 >>> for t in tests:
535 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000536 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000537 3 SampleClass.NestedClass
538 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000539 0 SampleClass.NestedClass.get
540 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000541 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000542 2 SampleClass.a_classmethod
543 1 SampleClass.a_property
544 1 SampleClass.a_staticmethod
545 1 SampleClass.double
546 1 SampleClass.get
547
Tim Peters8485b562004-08-04 18:46:34 +0000548Turning off Recursion
549~~~~~~~~~~~~~~~~~~~~~
550DocTestFinder can be told not to look for tests in contained objects
551using the `recurse` flag:
552
553 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000554 >>> for t in tests:
555 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000556 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000557
558Line numbers
559~~~~~~~~~~~~
560DocTestFinder finds the line number of each example:
561
562 >>> def f(x):
563 ... '''
564 ... >>> x = 12
565 ...
566 ... some text
567 ...
568 ... >>> # examples are not created for comments & bare prompts.
569 ... >>>
570 ... ...
571 ...
572 ... >>> for x in range(10):
573 ... ... print x,
574 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000575 ... >>> x//2
576 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000577 ... '''
578 >>> test = doctest.DocTestFinder().find(f)[0]
579 >>> [e.lineno for e in test.examples]
580 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000581"""
582
Edward Loper00f8da72004-08-26 18:05:07 +0000583def test_DocTestParser(): r"""
584Unit tests for the `DocTestParser` class.
585
586DocTestParser is used to parse docstrings containing doctest examples.
587
588The `parse` method divides a docstring into examples and intervening
589text:
590
591 >>> s = '''
592 ... >>> x, y = 2, 3 # no output expected
593 ... >>> if 1:
594 ... ... print x
595 ... ... print y
596 ... 2
597 ... 3
598 ...
599 ... Some text.
600 ... >>> x+y
601 ... 5
602 ... '''
603 >>> parser = doctest.DocTestParser()
604 >>> for piece in parser.parse(s):
605 ... if isinstance(piece, doctest.Example):
606 ... print 'Example:', (piece.source, piece.want, piece.lineno)
607 ... else:
Brett Cannon0b70cca2006-08-25 02:59:59 +0000608 ... print ' Text:', repr(piece)
Edward Loper00f8da72004-08-26 18:05:07 +0000609 Text: '\n'
610 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
611 Text: ''
612 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
613 Text: '\nSome text.\n'
614 Example: ('x+y\n', '5\n', 9)
615 Text: ''
616
617The `get_examples` method returns just the examples:
618
619 >>> for piece in parser.get_examples(s):
620 ... print (piece.source, piece.want, piece.lineno)
621 ('x, y = 2, 3 # no output expected\n', '', 1)
622 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
623 ('x+y\n', '5\n', 9)
624
625The `get_doctest` method creates a Test from the examples, along with the
626given arguments:
627
628 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
629 >>> (test.name, test.filename, test.lineno)
630 ('name', 'filename', 5)
631 >>> for piece in test.examples:
632 ... print (piece.source, piece.want, piece.lineno)
633 ('x, y = 2, 3 # no output expected\n', '', 1)
634 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
635 ('x+y\n', '5\n', 9)
636"""
637
Tim Peters8485b562004-08-04 18:46:34 +0000638class test_DocTestRunner:
639 def basics(): r"""
640Unit tests for the `DocTestRunner` class.
641
642DocTestRunner is used to run DocTest test cases, and to accumulate
643statistics. Here's a simple DocTest case we can use:
644
645 >>> def f(x):
646 ... '''
647 ... >>> x = 12
648 ... >>> print x
649 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000650 ... >>> x//2
651 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000652 ... '''
653 >>> test = doctest.DocTestFinder().find(f)[0]
654
655The main DocTestRunner interface is the `run` method, which runs a
656given DocTest case in a given namespace (globs). It returns a tuple
657`(f,t)`, where `f` is the number of failed tests and `t` is the number
658of tried tests.
659
660 >>> doctest.DocTestRunner(verbose=False).run(test)
661 (0, 3)
662
663If any example produces incorrect output, then the test runner reports
664the failure and proceeds to the next example:
665
666 >>> def f(x):
667 ... '''
668 ... >>> x = 12
669 ... >>> print x
670 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000671 ... >>> x//2
672 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000673 ... '''
674 >>> test = doctest.DocTestFinder().find(f)[0]
675 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000676 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000677 Trying:
678 x = 12
679 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000680 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000681 Trying:
682 print x
683 Expecting:
684 14
Tim Peters8485b562004-08-04 18:46:34 +0000685 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000686 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000687 Failed example:
688 print x
689 Expected:
690 14
691 Got:
692 12
Edward Loperaacf0832004-08-26 01:19:50 +0000693 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000694 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000695 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000696 6
Tim Peters8485b562004-08-04 18:46:34 +0000697 ok
698 (1, 3)
699"""
700 def verbose_flag(): r"""
701The `verbose` flag makes the test runner generate more detailed
702output:
703
704 >>> def f(x):
705 ... '''
706 ... >>> x = 12
707 ... >>> print x
708 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000709 ... >>> x//2
710 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000711 ... '''
712 >>> test = doctest.DocTestFinder().find(f)[0]
713
714 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000715 Trying:
716 x = 12
717 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000718 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000719 Trying:
720 print x
721 Expecting:
722 12
Tim Peters8485b562004-08-04 18:46:34 +0000723 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000724 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000725 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000726 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000727 6
Tim Peters8485b562004-08-04 18:46:34 +0000728 ok
729 (0, 3)
730
731If the `verbose` flag is unspecified, then the output will be verbose
732iff `-v` appears in sys.argv:
733
734 >>> # Save the real sys.argv list.
735 >>> old_argv = sys.argv
736
737 >>> # If -v does not appear in sys.argv, then output isn't verbose.
738 >>> sys.argv = ['test']
739 >>> doctest.DocTestRunner().run(test)
740 (0, 3)
741
742 >>> # If -v does appear in sys.argv, then output is verbose.
743 >>> sys.argv = ['test', '-v']
744 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000745 Trying:
746 x = 12
747 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000748 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000749 Trying:
750 print x
751 Expecting:
752 12
Tim Peters8485b562004-08-04 18:46:34 +0000753 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000754 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000755 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000756 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000757 6
Tim Peters8485b562004-08-04 18:46:34 +0000758 ok
759 (0, 3)
760
761 >>> # Restore sys.argv
762 >>> sys.argv = old_argv
763
764In the remaining examples, the test runner's verbosity will be
765explicitly set, to ensure that the test behavior is consistent.
766 """
767 def exceptions(): r"""
768Tests of `DocTestRunner`'s exception handling.
769
770An expected exception is specified with a traceback message. The
771lines between the first line and the type/value may be omitted or
772replaced with any other string:
773
774 >>> def f(x):
775 ... '''
776 ... >>> x = 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000777 ... >>> print x//0
Tim Peters8485b562004-08-04 18:46:34 +0000778 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000779 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000780 ... '''
781 >>> test = doctest.DocTestFinder().find(f)[0]
782 >>> doctest.DocTestRunner(verbose=False).run(test)
783 (0, 2)
784
Edward Loper19b19582004-08-25 23:07:03 +0000785An example may not generate output before it raises an exception; if
786it does, then the traceback message will not be recognized as
787signaling an expected exception, so the example will be reported as an
788unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000789
790 >>> def f(x):
791 ... '''
792 ... >>> x = 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000793 ... >>> print 'pre-exception output', x//0
Tim Peters8485b562004-08-04 18:46:34 +0000794 ... pre-exception output
795 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000796 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000797 ... '''
798 >>> test = doctest.DocTestFinder().find(f)[0]
799 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000800 ... # doctest: +ELLIPSIS
801 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000802 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000803 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000804 print 'pre-exception output', x//0
Edward Loper19b19582004-08-25 23:07:03 +0000805 Exception raised:
806 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000807 ZeroDivisionError: integer division or modulo by zero
Edward Loper19b19582004-08-25 23:07:03 +0000808 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000809
810Exception messages may contain newlines:
811
812 >>> def f(x):
813 ... r'''
814 ... >>> raise ValueError, 'multi\nline\nmessage'
815 ... Traceback (most recent call last):
816 ... ValueError: multi
817 ... line
818 ... message
819 ... '''
820 >>> test = doctest.DocTestFinder().find(f)[0]
821 >>> doctest.DocTestRunner(verbose=False).run(test)
822 (0, 1)
823
824If an exception is expected, but an exception with the wrong type or
825message is raised, then it is reported as a failure:
826
827 >>> def f(x):
828 ... r'''
829 ... >>> raise ValueError, 'message'
830 ... Traceback (most recent call last):
831 ... ValueError: wrong message
832 ... '''
833 >>> test = doctest.DocTestFinder().find(f)[0]
834 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000835 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000836 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000837 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000838 Failed example:
839 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000840 Expected:
841 Traceback (most recent call last):
842 ValueError: wrong message
843 Got:
844 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000845 ...
Tim Peters8485b562004-08-04 18:46:34 +0000846 ValueError: message
847 (1, 1)
848
Tim Peters1fbf9c52004-09-04 17:21:02 +0000849However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
850detail:
851
852 >>> def f(x):
853 ... r'''
854 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
855 ... Traceback (most recent call last):
856 ... ValueError: wrong message
857 ... '''
858 >>> test = doctest.DocTestFinder().find(f)[0]
859 >>> doctest.DocTestRunner(verbose=False).run(test)
860 (0, 1)
861
862But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
863
864 >>> def f(x):
865 ... r'''
866 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
867 ... Traceback (most recent call last):
868 ... TypeError: wrong type
869 ... '''
870 >>> test = doctest.DocTestFinder().find(f)[0]
871 >>> doctest.DocTestRunner(verbose=False).run(test)
872 ... # doctest: +ELLIPSIS
873 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000874 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000875 Failed example:
876 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
877 Expected:
878 Traceback (most recent call last):
879 TypeError: wrong type
880 Got:
881 Traceback (most recent call last):
882 ...
883 ValueError: message
884 (1, 1)
885
Tim Peters8485b562004-08-04 18:46:34 +0000886If an exception is raised but not expected, then it is reported as an
887unexpected exception:
888
Tim Peters8485b562004-08-04 18:46:34 +0000889 >>> def f(x):
890 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000891 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000892 ... 0
893 ... '''
894 >>> test = doctest.DocTestFinder().find(f)[0]
895 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000896 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000897 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000898 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000899 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000900 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000901 Exception raised:
902 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000903 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000904 ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000905 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000906"""
907 def optionflags(): r"""
908Tests of `DocTestRunner`'s option flag handling.
909
910Several option flags can be used to customize the behavior of the test
911runner. These are defined as module constants in doctest, and passed
912to the DocTestRunner constructor (multiple constants should be or-ed
913together).
914
915The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
916and 1/0:
917
918 >>> def f(x):
919 ... '>>> True\n1\n'
920
921 >>> # Without the flag:
922 >>> test = doctest.DocTestFinder().find(f)[0]
923 >>> doctest.DocTestRunner(verbose=False).run(test)
924 (0, 1)
925
926 >>> # With the flag:
927 >>> test = doctest.DocTestFinder().find(f)[0]
928 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
929 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000930 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000931 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000932 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000933 Failed example:
934 True
935 Expected:
936 1
937 Got:
938 True
Tim Peters8485b562004-08-04 18:46:34 +0000939 (1, 1)
940
941The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
942and the '<BLANKLINE>' marker:
943
944 >>> def f(x):
945 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
946
947 >>> # Without the flag:
948 >>> test = doctest.DocTestFinder().find(f)[0]
949 >>> doctest.DocTestRunner(verbose=False).run(test)
950 (0, 1)
951
952 >>> # With the flag:
953 >>> test = doctest.DocTestFinder().find(f)[0]
954 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
955 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000956 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000957 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000958 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000959 Failed example:
960 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000961 Expected:
962 a
963 <BLANKLINE>
964 b
965 Got:
966 a
967 <BLANKLINE>
968 b
969 (1, 1)
970
971The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
972treated as equal:
973
974 >>> def f(x):
975 ... '>>> print 1, 2, 3\n 1 2\n 3'
976
977 >>> # Without the flag:
978 >>> test = doctest.DocTestFinder().find(f)[0]
979 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000980 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000981 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000982 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000983 Failed example:
984 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000985 Expected:
986 1 2
987 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000988 Got:
989 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000990 (1, 1)
991
992 >>> # With the flag:
993 >>> test = doctest.DocTestFinder().find(f)[0]
994 >>> flags = doctest.NORMALIZE_WHITESPACE
995 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
996 (0, 1)
997
Tim Peters026f8dc2004-08-19 16:38:58 +0000998 An example from the docs:
999 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
1000 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1001 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1002
Tim Peters8485b562004-08-04 18:46:34 +00001003The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1004output to match any substring in the actual output:
1005
1006 >>> def f(x):
1007 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1008
1009 >>> # Without the flag:
1010 >>> test = doctest.DocTestFinder().find(f)[0]
1011 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001012 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001013 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001014 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001015 Failed example:
1016 print range(15)
1017 Expected:
1018 [0, 1, 2, ..., 14]
1019 Got:
1020 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +00001021 (1, 1)
1022
1023 >>> # With the flag:
1024 >>> test = doctest.DocTestFinder().find(f)[0]
1025 >>> flags = doctest.ELLIPSIS
1026 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1027 (0, 1)
1028
Tim Peterse594bee2004-08-22 01:47:51 +00001029 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001030
1031 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001032 ... print i**2, #doctest: +ELLIPSIS
1033 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001034
Tim Peters026f8dc2004-08-19 16:38:58 +00001035 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001036
1037 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001038 ... print i,
1039 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001040
Tim Peters026f8dc2004-08-19 16:38:58 +00001041 Examples from the docs:
1042
1043 >>> print range(20) # doctest:+ELLIPSIS
1044 [0, 1, ..., 18, 19]
1045
1046 >>> print range(20) # doctest: +ELLIPSIS
1047 ... # doctest: +NORMALIZE_WHITESPACE
1048 [0, 1, ..., 18, 19]
1049
Thomas Wouters477c8d52006-05-27 19:21:47 +00001050The SKIP flag causes an example to be skipped entirely. I.e., the
1051example is not run. It can be useful in contexts where doctest
1052examples serve as both documentation and test cases, and an example
1053should be included for documentation purposes, but should not be
1054checked (e.g., because its output is random, or depends on resources
1055which would be unavailable.) The SKIP flag can also be used for
1056'commenting out' broken examples.
1057
1058 >>> import unavailable_resource # doctest: +SKIP
1059 >>> unavailable_resource.do_something() # doctest: +SKIP
1060 >>> unavailable_resource.blow_up() # doctest: +SKIP
1061 Traceback (most recent call last):
1062 ...
1063 UncheckedBlowUpError: Nobody checks me.
1064
1065 >>> import random
1066 >>> print random.random() # doctest: +SKIP
1067 0.721216923889
1068
Edward Loper71f55af2004-08-26 01:41:51 +00001069The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001070and actual outputs to be displayed using a unified diff:
1071
1072 >>> def f(x):
1073 ... r'''
1074 ... >>> print '\n'.join('abcdefg')
1075 ... a
1076 ... B
1077 ... c
1078 ... d
1079 ... f
1080 ... g
1081 ... h
1082 ... '''
1083
1084 >>> # Without the flag:
1085 >>> test = doctest.DocTestFinder().find(f)[0]
1086 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001087 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001088 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001089 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001090 Failed example:
1091 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001092 Expected:
1093 a
1094 B
1095 c
1096 d
1097 f
1098 g
1099 h
1100 Got:
1101 a
1102 b
1103 c
1104 d
1105 e
1106 f
1107 g
1108 (1, 1)
1109
1110 >>> # With the flag:
1111 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001112 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001113 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001114 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001115 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001116 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001117 Failed example:
1118 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001119 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001120 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001121 a
1122 -B
1123 +b
1124 c
1125 d
1126 +e
1127 f
1128 g
1129 -h
Tim Peters8485b562004-08-04 18:46:34 +00001130 (1, 1)
1131
Edward Loper71f55af2004-08-26 01:41:51 +00001132The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001133and actual outputs to be displayed using a context diff:
1134
Edward Loper71f55af2004-08-26 01:41:51 +00001135 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001136 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001137 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001138 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001139 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001140 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001141 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001142 Failed example:
1143 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001144 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001145 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001146 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001147 a
1148 ! B
1149 c
1150 d
1151 f
1152 g
1153 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001154 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001155 a
1156 ! b
1157 c
1158 d
1159 + e
1160 f
1161 g
Tim Peters8485b562004-08-04 18:46:34 +00001162 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001163
1164
Edward Loper71f55af2004-08-26 01:41:51 +00001165The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001166used by the popular ndiff.py utility. This does intraline difference
1167marking, as well as interline differences.
1168
1169 >>> def f(x):
1170 ... r'''
1171 ... >>> print "a b c d e f g h i j k l m"
1172 ... a b c d e f g h i j k 1 m
1173 ... '''
1174 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001175 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001176 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001177 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001178 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001179 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001180 Failed example:
1181 print "a b c d e f g h i j k l m"
1182 Differences (ndiff with -expected +actual):
1183 - a b c d e f g h i j k 1 m
1184 ? ^
1185 + a b c d e f g h i j k l m
1186 ? + ++ ^
Tim Petersc6cbab02004-08-22 19:43:28 +00001187 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001188
1189The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1190failing example:
1191
1192 >>> def f(x):
1193 ... r'''
1194 ... >>> print 1 # first success
1195 ... 1
1196 ... >>> print 2 # first failure
1197 ... 200
1198 ... >>> print 3 # second failure
1199 ... 300
1200 ... >>> print 4 # second success
1201 ... 4
1202 ... >>> print 5 # third failure
1203 ... 500
1204 ... '''
1205 >>> test = doctest.DocTestFinder().find(f)[0]
1206 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1207 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001208 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001209 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001210 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001211 Failed example:
1212 print 2 # first failure
1213 Expected:
1214 200
1215 Got:
1216 2
1217 (3, 5)
1218
1219However, output from `report_start` is not supressed:
1220
1221 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001222 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001223 Trying:
1224 print 1 # first success
1225 Expecting:
1226 1
1227 ok
1228 Trying:
1229 print 2 # first failure
1230 Expecting:
1231 200
1232 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001233 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001234 Failed example:
1235 print 2 # first failure
1236 Expected:
1237 200
1238 Got:
1239 2
1240 (3, 5)
1241
1242For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1243count as failures:
1244
1245 >>> def f(x):
1246 ... r'''
1247 ... >>> print 1 # first success
1248 ... 1
1249 ... >>> raise ValueError(2) # first failure
1250 ... 200
1251 ... >>> print 3 # second failure
1252 ... 300
1253 ... >>> print 4 # second success
1254 ... 4
1255 ... >>> print 5 # third failure
1256 ... 500
1257 ... '''
1258 >>> test = doctest.DocTestFinder().find(f)[0]
1259 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1260 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1261 ... # doctest: +ELLIPSIS
1262 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001263 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001264 Failed example:
1265 raise ValueError(2) # first failure
1266 Exception raised:
1267 ...
1268 ValueError: 2
1269 (3, 5)
1270
Thomas Wouters477c8d52006-05-27 19:21:47 +00001271New option flags can also be registered, via register_optionflag(). Here
1272we reach into doctest's internals a bit.
1273
1274 >>> unlikely = "UNLIKELY_OPTION_NAME"
1275 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1276 False
1277 >>> new_flag_value = doctest.register_optionflag(unlikely)
1278 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1279 True
1280
1281Before 2.4.4/2.5, registering a name more than once erroneously created
1282more than one flag value. Here we verify that's fixed:
1283
1284 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1285 >>> redundant_flag_value == new_flag_value
1286 True
1287
1288Clean up.
1289 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1290
Tim Petersc6cbab02004-08-22 19:43:28 +00001291 """
1292
Tim Peters8485b562004-08-04 18:46:34 +00001293 def option_directives(): r"""
1294Tests of `DocTestRunner`'s option directive mechanism.
1295
Edward Loper74bca7a2004-08-12 02:27:44 +00001296Option directives can be used to turn option flags on or off for a
1297single example. To turn an option on for an example, follow that
1298example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001299
1300 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001301 ... >>> print range(10) # should fail: no ellipsis
1302 ... [0, 1, ..., 9]
1303 ...
1304 ... >>> print range(10) # doctest: +ELLIPSIS
1305 ... [0, 1, ..., 9]
1306 ... '''
1307 >>> test = doctest.DocTestFinder().find(f)[0]
1308 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001309 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001310 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001311 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001312 Failed example:
1313 print range(10) # should fail: no ellipsis
1314 Expected:
1315 [0, 1, ..., 9]
1316 Got:
1317 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001318 (1, 2)
1319
1320To turn an option off for an example, follow that example with a
1321comment of the form ``# doctest: -OPTION``:
1322
1323 >>> def f(x): r'''
1324 ... >>> print range(10)
1325 ... [0, 1, ..., 9]
1326 ...
1327 ... >>> # should fail: no ellipsis
1328 ... >>> print range(10) # doctest: -ELLIPSIS
1329 ... [0, 1, ..., 9]
1330 ... '''
1331 >>> test = doctest.DocTestFinder().find(f)[0]
1332 >>> doctest.DocTestRunner(verbose=False,
1333 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001334 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001335 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001336 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001337 Failed example:
1338 print range(10) # doctest: -ELLIPSIS
1339 Expected:
1340 [0, 1, ..., 9]
1341 Got:
1342 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001343 (1, 2)
1344
1345Option directives affect only the example that they appear with; they
1346do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001347
Edward Loper74bca7a2004-08-12 02:27:44 +00001348 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001349 ... >>> print range(10) # Should fail: no ellipsis
1350 ... [0, 1, ..., 9]
1351 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001352 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001353 ... [0, 1, ..., 9]
1354 ...
Tim Peters8485b562004-08-04 18:46:34 +00001355 ... >>> print range(10) # Should fail: no ellipsis
1356 ... [0, 1, ..., 9]
1357 ... '''
1358 >>> test = doctest.DocTestFinder().find(f)[0]
1359 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001360 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001361 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001362 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001363 Failed example:
1364 print range(10) # Should fail: no ellipsis
1365 Expected:
1366 [0, 1, ..., 9]
1367 Got:
1368 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001369 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001370 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001371 Failed example:
1372 print range(10) # Should fail: no ellipsis
1373 Expected:
1374 [0, 1, ..., 9]
1375 Got:
1376 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001377 (2, 3)
1378
Edward Loper74bca7a2004-08-12 02:27:44 +00001379Multiple options may be modified by a single option directive. They
1380may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001381
1382 >>> def f(x): r'''
1383 ... >>> print range(10) # Should fail
1384 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001385 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001386 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001387 ... [0, 1, ..., 9]
1388 ... '''
1389 >>> test = doctest.DocTestFinder().find(f)[0]
1390 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001391 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001392 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001393 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001394 Failed example:
1395 print range(10) # Should fail
1396 Expected:
1397 [0, 1, ..., 9]
1398 Got:
1399 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001400 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001401
1402 >>> def f(x): r'''
1403 ... >>> print range(10) # Should fail
1404 ... [0, 1, ..., 9]
1405 ... >>> print range(10) # Should succeed
1406 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1407 ... [0, 1, ..., 9]
1408 ... '''
1409 >>> test = doctest.DocTestFinder().find(f)[0]
1410 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001411 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001412 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001413 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001414 Failed example:
1415 print range(10) # Should fail
1416 Expected:
1417 [0, 1, ..., 9]
1418 Got:
1419 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001420 (1, 2)
1421
1422 >>> def f(x): r'''
1423 ... >>> print range(10) # Should fail
1424 ... [0, 1, ..., 9]
1425 ... >>> print range(10) # Should succeed
1426 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1427 ... [0, 1, ..., 9]
1428 ... '''
1429 >>> test = doctest.DocTestFinder().find(f)[0]
1430 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001431 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001432 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001433 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001434 Failed example:
1435 print range(10) # Should fail
1436 Expected:
1437 [0, 1, ..., 9]
1438 Got:
1439 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001440 (1, 2)
1441
1442The option directive may be put on the line following the source, as
1443long as a continuation prompt is used:
1444
1445 >>> def f(x): r'''
1446 ... >>> print range(10)
1447 ... ... # doctest: +ELLIPSIS
1448 ... [0, 1, ..., 9]
1449 ... '''
1450 >>> test = doctest.DocTestFinder().find(f)[0]
1451 >>> doctest.DocTestRunner(verbose=False).run(test)
1452 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001453
Edward Loper74bca7a2004-08-12 02:27:44 +00001454For examples with multi-line source, the option directive may appear
1455at the end of any line:
1456
1457 >>> def f(x): r'''
1458 ... >>> for x in range(10): # doctest: +ELLIPSIS
1459 ... ... print x,
1460 ... 0 1 2 ... 9
1461 ...
1462 ... >>> for x in range(10):
1463 ... ... print x, # doctest: +ELLIPSIS
1464 ... 0 1 2 ... 9
1465 ... '''
1466 >>> test = doctest.DocTestFinder().find(f)[0]
1467 >>> doctest.DocTestRunner(verbose=False).run(test)
1468 (0, 2)
1469
1470If more than one line of an example with multi-line source has an
1471option directive, then they are combined:
1472
1473 >>> def f(x): r'''
1474 ... Should fail (option directive not on the last line):
1475 ... >>> for x in range(10): # doctest: +ELLIPSIS
1476 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1477 ... 0 1 2...9
1478 ... '''
1479 >>> test = doctest.DocTestFinder().find(f)[0]
1480 >>> doctest.DocTestRunner(verbose=False).run(test)
1481 (0, 1)
1482
1483It is an error to have a comment of the form ``# doctest:`` that is
1484*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1485``OPTION`` is an option that has been registered with
1486`register_option`:
1487
1488 >>> # Error: Option not registered
1489 >>> s = '>>> print 12 #doctest: +BADOPTION'
1490 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1491 Traceback (most recent call last):
1492 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1493
1494 >>> # Error: No + or - prefix
1495 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1496 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1497 Traceback (most recent call last):
1498 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1499
1500It is an error to use an option directive on a line that contains no
1501source:
1502
1503 >>> s = '>>> # doctest: +ELLIPSIS'
1504 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1505 Traceback (most recent call last):
1506 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 +00001507"""
1508
1509def test_testsource(): r"""
1510Unit tests for `testsource()`.
1511
1512The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001513test with that name in that module, and converts it to a script. The
1514example code is converted to regular Python code. The surrounding
1515words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001516
1517 >>> import test.test_doctest
1518 >>> name = 'test.test_doctest.sample_func'
1519 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001520 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001521 #
Tim Peters8485b562004-08-04 18:46:34 +00001522 print sample_func(22)
1523 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001524 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001525 #
Edward Lopera5db6002004-08-12 02:41:30 +00001526 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001527 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001528
1529 >>> name = 'test.test_doctest.SampleNewStyleClass'
1530 >>> print doctest.testsource(test.test_doctest, name)
1531 print '1\n2\n3'
1532 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001533 ## 1
1534 ## 2
1535 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001536 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001537
1538 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1539 >>> print doctest.testsource(test.test_doctest, name)
1540 print SampleClass.a_classmethod(10)
1541 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001542 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001543 print SampleClass(0).a_classmethod(10)
1544 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001545 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001546 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001547"""
1548
1549def test_debug(): r"""
1550
1551Create a docstring that we want to debug:
1552
1553 >>> s = '''
1554 ... >>> x = 12
1555 ... >>> print x
1556 ... 12
1557 ... '''
1558
1559Create some fake stdin input, to feed to the debugger:
1560
1561 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001562 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001563 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001564
1565Run the debugger on the docstring, and then restore sys.stdin.
1566
Edward Loper2de91ba2004-08-27 02:07:46 +00001567 >>> try: doctest.debug_src(s)
1568 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001569 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001570 (Pdb) next
1571 12
Tim Peters8485b562004-08-04 18:46:34 +00001572 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001573 > <string>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001574 (Pdb) print x
1575 12
1576 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001577
1578"""
1579
Jim Fulton356fd192004-08-09 11:34:47 +00001580def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001581 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001582
Tim Peters413ced62004-08-09 15:43:47 +00001583 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001584 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001585 you use it. The doctest module changes sys.stdout so that it can
1586 capture program output. It also temporarily replaces pdb.set_trace
1587 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001588 see debugger output.
1589
1590 >>> doc = '''
1591 ... >>> x = 42
1592 ... >>> import pdb; pdb.set_trace()
1593 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001594 >>> parser = doctest.DocTestParser()
1595 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001596 >>> runner = doctest.DocTestRunner(verbose=False)
1597
1598 To demonstrate this, we'll create a fake standard input that
1599 captures our debugger input:
1600
1601 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001602 >>> real_stdin = sys.stdin
1603 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001604 ... 'print x', # print data defined by the example
1605 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001606 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001607
Edward Loper2de91ba2004-08-27 02:07:46 +00001608 >>> try: runner.run(test)
1609 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001610 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001611 > <doctest foo[1]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001612 -> import pdb; pdb.set_trace()
1613 (Pdb) print x
1614 42
1615 (Pdb) continue
1616 (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001617
1618 You can also put pdb.set_trace in a function called from a test:
1619
1620 >>> def calls_set_trace():
1621 ... y=2
1622 ... import pdb; pdb.set_trace()
1623
1624 >>> doc = '''
1625 ... >>> x=1
1626 ... >>> calls_set_trace()
1627 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001628 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001629 >>> real_stdin = sys.stdin
1630 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001631 ... 'print y', # print data defined in the function
1632 ... 'up', # out of function
1633 ... 'print x', # print data defined by the example
1634 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001635 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001636
Tim Peters50c6bdb2004-11-08 22:07:37 +00001637 >>> try:
1638 ... runner.run(test)
1639 ... finally:
1640 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001641 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001642 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1643 -> import pdb; pdb.set_trace()
1644 (Pdb) print y
1645 2
1646 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001647 > <doctest foo[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001648 -> calls_set_trace()
1649 (Pdb) print x
1650 1
1651 (Pdb) continue
1652 (0, 2)
1653
1654 During interactive debugging, source code is shown, even for
1655 doctest examples:
1656
1657 >>> doc = '''
1658 ... >>> def f(x):
1659 ... ... g(x*2)
1660 ... >>> def g(x):
1661 ... ... print x+3
1662 ... ... import pdb; pdb.set_trace()
1663 ... >>> f(3)
1664 ... '''
1665 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1666 >>> real_stdin = sys.stdin
1667 >>> sys.stdin = _FakeInput([
1668 ... 'list', # list source from example 2
1669 ... 'next', # return from g()
1670 ... 'list', # list source from example 1
1671 ... 'next', # return from f()
1672 ... 'list', # list source from example 3
1673 ... 'continue', # stop debugging
1674 ... ''])
1675 >>> try: runner.run(test)
1676 ... finally: sys.stdin = real_stdin
1677 ... # doctest: +NORMALIZE_WHITESPACE
1678 --Return--
1679 > <doctest foo[1]>(3)g()->None
1680 -> import pdb; pdb.set_trace()
1681 (Pdb) list
1682 1 def g(x):
1683 2 print x+3
1684 3 -> import pdb; pdb.set_trace()
1685 [EOF]
1686 (Pdb) next
1687 --Return--
1688 > <doctest foo[0]>(2)f()->None
1689 -> g(x*2)
1690 (Pdb) list
1691 1 def f(x):
1692 2 -> g(x*2)
1693 [EOF]
1694 (Pdb) next
1695 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696 > <doctest foo[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001697 -> f(3)
1698 (Pdb) list
1699 1 -> f(3)
1700 [EOF]
1701 (Pdb) continue
1702 **********************************************************************
1703 File "foo.py", line 7, in foo
1704 Failed example:
1705 f(3)
1706 Expected nothing
1707 Got:
1708 9
1709 (1, 3)
Jim Fulton356fd192004-08-09 11:34:47 +00001710 """
1711
Tim Peters50c6bdb2004-11-08 22:07:37 +00001712def test_pdb_set_trace_nested():
1713 """This illustrates more-demanding use of set_trace with nested functions.
1714
1715 >>> class C(object):
1716 ... def calls_set_trace(self):
1717 ... y = 1
1718 ... import pdb; pdb.set_trace()
1719 ... self.f1()
1720 ... y = 2
1721 ... def f1(self):
1722 ... x = 1
1723 ... self.f2()
1724 ... x = 2
1725 ... def f2(self):
1726 ... z = 1
1727 ... z = 2
1728
1729 >>> calls_set_trace = C().calls_set_trace
1730
1731 >>> doc = '''
1732 ... >>> a = 1
1733 ... >>> calls_set_trace()
1734 ... '''
1735 >>> parser = doctest.DocTestParser()
1736 >>> runner = doctest.DocTestRunner(verbose=False)
1737 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1738 >>> real_stdin = sys.stdin
1739 >>> sys.stdin = _FakeInput([
1740 ... 'print y', # print data defined in the function
1741 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z',
1742 ... 'up', 'print x',
1743 ... 'up', 'print y',
1744 ... 'up', 'print foo',
1745 ... 'continue', # stop debugging
1746 ... ''])
1747
1748 >>> try:
1749 ... runner.run(test)
1750 ... finally:
1751 ... sys.stdin = real_stdin
1752 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1753 -> self.f1()
1754 (Pdb) print y
1755 1
1756 (Pdb) step
1757 --Call--
1758 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1759 -> def f1(self):
1760 (Pdb) step
1761 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1762 -> x = 1
1763 (Pdb) step
1764 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1765 -> self.f2()
1766 (Pdb) step
1767 --Call--
1768 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1769 -> def f2(self):
1770 (Pdb) step
1771 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1772 -> z = 1
1773 (Pdb) step
1774 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1775 -> z = 2
1776 (Pdb) print z
1777 1
1778 (Pdb) up
1779 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1780 -> self.f2()
1781 (Pdb) print x
1782 1
1783 (Pdb) up
1784 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1785 -> self.f1()
1786 (Pdb) print y
1787 1
1788 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001789 > <doctest foo[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001790 -> calls_set_trace()
1791 (Pdb) print foo
1792 *** NameError: name 'foo' is not defined
1793 (Pdb) continue
1794 (0, 2)
1795"""
1796
Tim Peters19397e52004-08-06 22:02:59 +00001797def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001798 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001799
1800 We create a Suite by providing a module. A module can be provided
1801 by passing a module object:
1802
1803 >>> import unittest
1804 >>> import test.sample_doctest
1805 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1806 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001807 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001808
1809 We can also supply the module by name:
1810
1811 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1812 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001813 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001814
1815 We can use the current module:
1816
1817 >>> suite = test.sample_doctest.test_suite()
1818 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001819 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001820
1821 We can supply global variables. If we pass globs, they will be
1822 used instead of the module globals. Here we'll pass an empty
1823 globals, triggering an extra error:
1824
1825 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1826 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001827 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001828
1829 Alternatively, we can provide extra globals. Here we'll make an
1830 error go away by providing an extra global variable:
1831
1832 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1833 ... extraglobs={'y': 1})
1834 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001835 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001836
1837 You can pass option flags. Here we'll cause an extra error
1838 by disabling the blank-line feature:
1839
1840 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001841 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001842 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001843 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001844
Tim Peters1e277ee2004-08-07 05:37:52 +00001845 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001846
Jim Fultonf54bad42004-08-28 14:57:56 +00001847 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001848 ... import test.test_doctest
1849 ... test.test_doctest.sillySetup = True
1850
Jim Fultonf54bad42004-08-28 14:57:56 +00001851 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001852 ... import test.test_doctest
1853 ... del test.test_doctest.sillySetup
1854
1855 Here, we installed a silly variable that the test expects:
1856
1857 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1858 ... setUp=setUp, tearDown=tearDown)
1859 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001860 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001861
1862 But the tearDown restores sanity:
1863
1864 >>> import test.test_doctest
1865 >>> test.test_doctest.sillySetup
1866 Traceback (most recent call last):
1867 ...
1868 AttributeError: 'module' object has no attribute 'sillySetup'
1869
Jim Fultonf54bad42004-08-28 14:57:56 +00001870 The setUp and tearDown funtions are passed test objects. Here
1871 we'll use the setUp function to supply the missing variable y:
1872
1873 >>> def setUp(test):
1874 ... test.globs['y'] = 1
1875
1876 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1877 >>> suite.run(unittest.TestResult())
1878 <unittest.TestResult run=9 errors=0 failures=3>
1879
1880 Here, we didn't need to use a tearDown function because we
1881 modified the test globals, which are a copy of the
1882 sample_doctest module dictionary. The test globals are
1883 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001884 """
1885
1886def test_DocFileSuite():
1887 """We can test tests found in text files using a DocFileSuite.
1888
1889 We create a suite by providing the names of one or more text
1890 files that include examples:
1891
1892 >>> import unittest
1893 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001894 ... 'test_doctest2.txt',
1895 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00001896 >>> suite.run(unittest.TestResult())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001897 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001898
1899 The test files are looked for in the directory containing the
1900 calling module. A package keyword argument can be provided to
1901 specify a different relative location.
1902
1903 >>> import unittest
1904 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1905 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001906 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001907 ... package='test')
1908 >>> suite.run(unittest.TestResult())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001909 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001910
Edward Loper0273f5b2004-09-18 20:27:04 +00001911 '/' should be used as a path separator. It will be converted
1912 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001913
1914 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1915 >>> suite.run(unittest.TestResult())
1916 <unittest.TestResult run=1 errors=0 failures=1>
1917
Edward Loper0273f5b2004-09-18 20:27:04 +00001918 If DocFileSuite is used from an interactive session, then files
1919 are resolved relative to the directory of sys.argv[0]:
1920
1921 >>> import new, os.path, test.test_doctest
1922 >>> save_argv = sys.argv
1923 >>> sys.argv = [test.test_doctest.__file__]
1924 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1925 ... package=new.module('__main__'))
1926 >>> sys.argv = save_argv
1927
Edward Loper052d0cd2004-09-19 17:19:33 +00001928 By setting `module_relative=False`, os-specific paths may be
1929 used (including absolute paths and paths relative to the
1930 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00001931
1932 >>> # Get the absolute path of the test package.
1933 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
1934 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
1935
1936 >>> # Use it to find the absolute path of test_doctest.txt.
1937 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
1938
Edward Loper052d0cd2004-09-19 17:19:33 +00001939 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00001940 >>> suite.run(unittest.TestResult())
1941 <unittest.TestResult run=1 errors=0 failures=1>
1942
Edward Loper052d0cd2004-09-19 17:19:33 +00001943 It is an error to specify `package` when `module_relative=False`:
1944
1945 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
1946 ... package='test')
1947 Traceback (most recent call last):
1948 ValueError: Package may only be specified for module-relative paths.
1949
Tim Peters19397e52004-08-06 22:02:59 +00001950 You can specify initial global variables:
1951
1952 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1953 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001954 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001955 ... globs={'favorite_color': 'blue'})
1956 >>> suite.run(unittest.TestResult())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001957 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001958
1959 In this case, we supplied a missing favorite color. You can
1960 provide doctest options:
1961
1962 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1963 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001964 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001965 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1966 ... globs={'favorite_color': 'blue'})
1967 >>> suite.run(unittest.TestResult())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001968 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001969
1970 And, you can provide setUp and tearDown functions:
1971
1972 You can supply setUp and teatDoen functions:
1973
Jim Fultonf54bad42004-08-28 14:57:56 +00001974 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001975 ... import test.test_doctest
1976 ... test.test_doctest.sillySetup = True
1977
Jim Fultonf54bad42004-08-28 14:57:56 +00001978 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001979 ... import test.test_doctest
1980 ... del test.test_doctest.sillySetup
1981
1982 Here, we installed a silly variable that the test expects:
1983
1984 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1985 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001986 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001987 ... setUp=setUp, tearDown=tearDown)
1988 >>> suite.run(unittest.TestResult())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001989 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001990
1991 But the tearDown restores sanity:
1992
1993 >>> import test.test_doctest
1994 >>> test.test_doctest.sillySetup
1995 Traceback (most recent call last):
1996 ...
1997 AttributeError: 'module' object has no attribute 'sillySetup'
1998
Jim Fultonf54bad42004-08-28 14:57:56 +00001999 The setUp and tearDown funtions are passed test objects.
2000 Here, we'll use a setUp function to set the favorite color in
2001 test_doctest.txt:
2002
2003 >>> def setUp(test):
2004 ... test.globs['favorite_color'] = 'blue'
2005
2006 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2007 >>> suite.run(unittest.TestResult())
2008 <unittest.TestResult run=1 errors=0 failures=0>
2009
2010 Here, we didn't need to use a tearDown function because we
2011 modified the test globals. The test globals are
2012 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002013
Fred Drake7c404a42004-12-21 23:46:34 +00002014 Tests in a file run using `DocFileSuite` can also access the
2015 `__file__` global, which is set to the name of the file
2016 containing the tests:
2017
2018 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2019 >>> suite.run(unittest.TestResult())
2020 <unittest.TestResult run=1 errors=0 failures=0>
2021
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002022 If the tests contain non-ASCII characters, we have to specify which
2023 encoding the file is encoded with. We do so by using the `encoding`
2024 parameter:
2025
2026 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2027 ... 'test_doctest2.txt',
2028 ... 'test_doctest4.txt',
2029 ... encoding='utf-8')
2030 >>> suite.run(unittest.TestResult())
2031 <unittest.TestResult run=3 errors=0 failures=2>
2032
Jim Fultonf54bad42004-08-28 14:57:56 +00002033 """
Tim Peters19397e52004-08-06 22:02:59 +00002034
Jim Fulton07a349c2004-08-22 14:10:00 +00002035def test_trailing_space_in_test():
2036 """
Tim Petersa7def722004-08-23 22:13:22 +00002037 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002038
Jim Fulton07a349c2004-08-22 14:10:00 +00002039 >>> x, y = 'foo', ''
2040 >>> print x, y
2041 foo \n
2042 """
Tim Peters19397e52004-08-06 22:02:59 +00002043
Jim Fultonf54bad42004-08-28 14:57:56 +00002044
2045def test_unittest_reportflags():
2046 """Default unittest reporting flags can be set to control reporting
2047
2048 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2049 only the first failure of each test. First, we'll look at the
2050 output without the flag. The file test_doctest.txt file has two
2051 tests. They both fail if blank lines are disabled:
2052
2053 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2054 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2055 >>> import unittest
2056 >>> result = suite.run(unittest.TestResult())
2057 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2058 Traceback ...
2059 Failed example:
2060 favorite_color
2061 ...
2062 Failed example:
2063 if 1:
2064 ...
2065
2066 Note that we see both failures displayed.
2067
2068 >>> old = doctest.set_unittest_reportflags(
2069 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2070
2071 Now, when we run the test:
2072
2073 >>> result = suite.run(unittest.TestResult())
2074 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2075 Traceback ...
2076 Failed example:
2077 favorite_color
2078 Exception raised:
2079 ...
2080 NameError: name 'favorite_color' is not defined
2081 <BLANKLINE>
2082 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002083
Jim Fultonf54bad42004-08-28 14:57:56 +00002084 We get only the first failure.
2085
2086 If we give any reporting options when we set up the tests,
2087 however:
2088
2089 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2090 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2091
2092 Then the default eporting options are ignored:
2093
2094 >>> result = suite.run(unittest.TestResult())
2095 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2096 Traceback ...
2097 Failed example:
2098 favorite_color
2099 ...
2100 Failed example:
2101 if 1:
2102 print 'a'
2103 print
2104 print 'b'
2105 Differences (ndiff with -expected +actual):
2106 a
2107 - <BLANKLINE>
2108 +
2109 b
2110 <BLANKLINE>
2111 <BLANKLINE>
2112
2113
2114 Test runners can restore the formatting flags after they run:
2115
2116 >>> ignored = doctest.set_unittest_reportflags(old)
2117
2118 """
2119
Edward Loper052d0cd2004-09-19 17:19:33 +00002120def test_testfile(): r"""
2121Tests for the `testfile()` function. This function runs all the
2122doctest examples in a given file. In its simple invokation, it is
2123called with the name of a file, which is taken to be relative to the
2124calling module. The return value is (#failures, #tests).
2125
2126 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2127 **********************************************************************
2128 File "...", line 6, in test_doctest.txt
2129 Failed example:
2130 favorite_color
2131 Exception raised:
2132 ...
2133 NameError: name 'favorite_color' is not defined
2134 **********************************************************************
2135 1 items had failures:
2136 1 of 2 in test_doctest.txt
2137 ***Test Failed*** 1 failures.
2138 (1, 2)
2139 >>> doctest.master = None # Reset master.
2140
2141(Note: we'll be clearing doctest.master after each call to
2142`doctest.testfile`, to supress warnings about multiple tests with the
2143same name.)
2144
2145Globals may be specified with the `globs` and `extraglobs` parameters:
2146
2147 >>> globs = {'favorite_color': 'blue'}
2148 >>> doctest.testfile('test_doctest.txt', globs=globs)
2149 (0, 2)
2150 >>> doctest.master = None # Reset master.
2151
2152 >>> extraglobs = {'favorite_color': 'red'}
2153 >>> doctest.testfile('test_doctest.txt', globs=globs,
2154 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2155 **********************************************************************
2156 File "...", line 6, in test_doctest.txt
2157 Failed example:
2158 favorite_color
2159 Expected:
2160 'blue'
2161 Got:
2162 'red'
2163 **********************************************************************
2164 1 items had failures:
2165 1 of 2 in test_doctest.txt
2166 ***Test Failed*** 1 failures.
2167 (1, 2)
2168 >>> doctest.master = None # Reset master.
2169
2170The file may be made relative to a given module or package, using the
2171optional `module_relative` parameter:
2172
2173 >>> doctest.testfile('test_doctest.txt', globs=globs,
2174 ... module_relative='test')
2175 (0, 2)
2176 >>> doctest.master = None # Reset master.
2177
2178Verbosity can be increased with the optional `verbose` paremter:
2179
2180 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2181 Trying:
2182 favorite_color
2183 Expecting:
2184 'blue'
2185 ok
2186 Trying:
2187 if 1:
2188 print 'a'
2189 print
2190 print 'b'
2191 Expecting:
2192 a
2193 <BLANKLINE>
2194 b
2195 ok
2196 1 items passed all tests:
2197 2 tests in test_doctest.txt
2198 2 tests in 1 items.
2199 2 passed and 0 failed.
2200 Test passed.
2201 (0, 2)
2202 >>> doctest.master = None # Reset master.
2203
2204The name of the test may be specified with the optional `name`
2205parameter:
2206
2207 >>> doctest.testfile('test_doctest.txt', name='newname')
2208 ... # doctest: +ELLIPSIS
2209 **********************************************************************
2210 File "...", line 6, in newname
2211 ...
2212 (1, 2)
2213 >>> doctest.master = None # Reset master.
2214
2215The summary report may be supressed with the optional `report`
2216parameter:
2217
2218 >>> doctest.testfile('test_doctest.txt', report=False)
2219 ... # doctest: +ELLIPSIS
2220 **********************************************************************
2221 File "...", line 6, in test_doctest.txt
2222 Failed example:
2223 favorite_color
2224 Exception raised:
2225 ...
2226 NameError: name 'favorite_color' is not defined
2227 (1, 2)
2228 >>> doctest.master = None # Reset master.
2229
2230The optional keyword argument `raise_on_error` can be used to raise an
2231exception on the first error (which may be useful for postmortem
2232debugging):
2233
2234 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2235 ... # doctest: +ELLIPSIS
2236 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002237 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002238 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002239
2240If the tests contain non-ASCII characters, the tests might fail, since
2241it's unknown which encoding is used. The encoding can be specified
2242using the optional keyword argument `encoding`:
2243
2244 >>> doctest.testfile('test_doctest4.txt') # doctest: +ELLIPSIS
2245 **********************************************************************
2246 File "...", line 7, in test_doctest4.txt
2247 Failed example:
2248 u'...'
2249 Expected:
2250 u'f\xf6\xf6'
2251 Got:
2252 u'f\xc3\xb6\xc3\xb6'
2253 **********************************************************************
2254 ...
2255 **********************************************************************
2256 1 items had failures:
2257 2 of 4 in test_doctest4.txt
2258 ***Test Failed*** 2 failures.
2259 (2, 4)
2260 >>> doctest.master = None # Reset master.
2261
2262 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
2263 (0, 4)
2264 >>> doctest.master = None # Reset master.
Edward Loper052d0cd2004-09-19 17:19:33 +00002265"""
2266
Tim Petersa7def722004-08-23 22:13:22 +00002267# old_test1, ... used to live in doctest.py, but cluttered it. Note
2268# that these use the deprecated doctest.Tester, so should go away (or
2269# be rewritten) someday.
2270
2271# Ignore all warnings about the use of class Tester in this module.
2272# Note that the name of this module may differ depending on how it's
2273# imported, so the use of __name__ is important.
2274warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2275 __name__, 0)
2276
2277def old_test1(): r"""
2278>>> from doctest import Tester
2279>>> t = Tester(globs={'x': 42}, verbose=0)
2280>>> t.runstring(r'''
2281... >>> x = x * 2
2282... >>> print x
2283... 42
2284... ''', 'XYZ')
2285**********************************************************************
2286Line 3, in XYZ
2287Failed example:
2288 print x
2289Expected:
2290 42
2291Got:
2292 84
2293(1, 2)
2294>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2295(0, 2)
2296>>> t.summarize()
2297**********************************************************************
22981 items had failures:
2299 1 of 2 in XYZ
2300***Test Failed*** 1 failures.
2301(1, 4)
2302>>> t.summarize(verbose=1)
23031 items passed all tests:
2304 2 tests in example2
2305**********************************************************************
23061 items had failures:
2307 1 of 2 in XYZ
23084 tests in 2 items.
23093 passed and 1 failed.
2310***Test Failed*** 1 failures.
2311(1, 4)
2312"""
2313
2314def old_test2(): r"""
2315 >>> from doctest import Tester
2316 >>> t = Tester(globs={}, verbose=1)
2317 >>> test = r'''
2318 ... # just an example
2319 ... >>> x = 1 + 2
2320 ... >>> x
2321 ... 3
2322 ... '''
2323 >>> t.runstring(test, "Example")
2324 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002325 Trying:
2326 x = 1 + 2
2327 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002328 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002329 Trying:
2330 x
2331 Expecting:
2332 3
Tim Petersa7def722004-08-23 22:13:22 +00002333 ok
2334 0 of 2 examples failed in string Example
2335 (0, 2)
2336"""
2337
2338def old_test3(): r"""
2339 >>> from doctest import Tester
2340 >>> t = Tester(globs={}, verbose=0)
2341 >>> def _f():
2342 ... '''Trivial docstring example.
2343 ... >>> assert 2 == 2
2344 ... '''
2345 ... return 32
2346 ...
2347 >>> t.rundoc(_f) # expect 0 failures in 1 example
2348 (0, 1)
2349"""
2350
2351def old_test4(): """
2352 >>> import new
2353 >>> m1 = new.module('_m1')
2354 >>> m2 = new.module('_m2')
2355 >>> test_data = \"""
2356 ... def _f():
2357 ... '''>>> assert 1 == 1
2358 ... '''
2359 ... def g():
2360 ... '''>>> assert 2 != 1
2361 ... '''
2362 ... class H:
2363 ... '''>>> assert 2 > 1
2364 ... '''
2365 ... def bar(self):
2366 ... '''>>> assert 1 < 2
2367 ... '''
2368 ... \"""
Georg Brandl7cae87c2006-09-06 06:51:57 +00002369 >>> exec(test_data, m1.__dict__)
2370 >>> exec(test_data, m2.__dict__)
Tim Petersa7def722004-08-23 22:13:22 +00002371 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2372
2373 Tests that objects outside m1 are excluded:
2374
2375 >>> from doctest import Tester
2376 >>> t = Tester(globs={}, verbose=0)
2377 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
2378 (0, 4)
2379
2380 Once more, not excluding stuff outside m1:
2381
2382 >>> t = Tester(globs={}, verbose=0)
2383 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2384 (0, 8)
2385
2386 The exclusion of objects from outside the designated module is
2387 meant to be invoked automagically by testmod.
2388
2389 >>> doctest.testmod(m1, verbose=False)
2390 (0, 4)
2391"""
2392
Tim Peters8485b562004-08-04 18:46:34 +00002393######################################################################
2394## Main
2395######################################################################
2396
2397def test_main():
2398 # Check the doctest cases in doctest itself:
2399 test_support.run_doctest(doctest, verbosity=True)
2400 # Check the doctest cases defined here:
2401 from test import test_doctest
2402 test_support.run_doctest(test_doctest, verbosity=True)
2403
2404import trace, sys, re, StringIO
2405def test_coverage(coverdir):
2406 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2407 trace=0, count=1)
2408 tracer.run('reload(doctest); test_main()')
2409 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002410 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002411 r.write_results(show_missing=True, summary=True,
2412 coverdir=coverdir)
2413
2414if __name__ == '__main__':
2415 if '-c' in sys.argv:
2416 test_coverage('/tmp/doctest.cover')
2417 else:
2418 test_main()