blob: 7f51ab547008d2eec15fb477af9aba0e8fa836f3 [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
28 """
29 def __init__(self, val):
30 """
31 >>> print SampleClass(12).get()
32 12
33 """
34 self.val = val
35
36 def double(self):
37 """
38 >>> print SampleClass(12).double().get()
39 24
40 """
41 return SampleClass(self.val + self.val)
42
43 def get(self):
44 """
45 >>> print SampleClass(-5).get()
46 -5
47 """
48 return self.val
49
50 def a_staticmethod(v):
51 """
52 >>> print SampleClass.a_staticmethod(10)
53 11
54 """
55 return v+1
56 a_staticmethod = staticmethod(a_staticmethod)
57
58 def a_classmethod(cls, v):
59 """
60 >>> print SampleClass.a_classmethod(10)
61 12
62 >>> print SampleClass(0).a_classmethod(10)
63 12
64 """
65 return v+2
66 a_classmethod = classmethod(a_classmethod)
67
68 a_property = property(get, doc="""
69 >>> print SampleClass(22).a_property
70 22
71 """)
72
73 class NestedClass:
74 """
75 >>> x = SampleClass.NestedClass(5)
76 >>> y = x.square()
77 >>> print y.get()
78 25
79 """
80 def __init__(self, val=0):
81 """
82 >>> print SampleClass.NestedClass().get()
83 0
84 """
85 self.val = val
86 def square(self):
87 return SampleClass.NestedClass(self.val*self.val)
88 def get(self):
89 return self.val
90
91class SampleNewStyleClass(object):
92 r"""
93 >>> print '1\n2\n3'
94 1
95 2
96 3
97 """
98 def __init__(self, val):
99 """
100 >>> print SampleNewStyleClass(12).get()
101 12
102 """
103 self.val = val
104
105 def double(self):
106 """
107 >>> print SampleNewStyleClass(12).double().get()
108 24
109 """
110 return SampleNewStyleClass(self.val + self.val)
111
112 def get(self):
113 """
114 >>> print SampleNewStyleClass(-5).get()
115 -5
116 """
117 return self.val
118
119######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000120## Fake stdin (for testing interactive debugging)
121######################################################################
122
123class _FakeInput:
124 """
125 A fake input stream for pdb's interactive debugger. Whenever a
126 line is read, print it (to simulate the user typing it), and then
127 return it. The set of lines to return is specified in the
128 constructor; they should not have trailing newlines.
129 """
130 def __init__(self, lines):
131 self.lines = lines
132
133 def readline(self):
134 line = self.lines.pop(0)
135 print line
136 return line+'\n'
137
138######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000139## Test Cases
140######################################################################
141
142def test_Example(): r"""
143Unit tests for the `Example` class.
144
Edward Lopera6b68322004-08-26 00:05:43 +0000145Example is a simple container class that holds:
146 - `source`: A source string.
147 - `want`: An expected output string.
148 - `exc_msg`: An expected exception message string (or None if no
149 exception is expected).
150 - `lineno`: A line number (within the docstring).
151 - `indent`: The example's indentation in the input string.
152 - `options`: An option dictionary, mapping option flags to True or
153 False.
Tim Peters8485b562004-08-04 18:46:34 +0000154
Edward Lopera6b68322004-08-26 00:05:43 +0000155These attributes are set by the constructor. `source` and `want` are
156required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000157
Edward Lopera6b68322004-08-26 00:05:43 +0000158 >>> example = doctest.Example('print 1', '1\n')
159 >>> (example.source, example.want, example.exc_msg,
160 ... example.lineno, example.indent, example.options)
161 ('print 1\n', '1\n', None, 0, 0, {})
162
163The first three attributes (`source`, `want`, and `exc_msg`) may be
164specified positionally; the remaining arguments should be specified as
165keyword arguments:
166
167 >>> exc_msg = 'IndexError: pop from an empty list'
168 >>> example = doctest.Example('[].pop()', '', exc_msg,
169 ... lineno=5, indent=4,
170 ... options={doctest.ELLIPSIS: True})
171 >>> (example.source, example.want, example.exc_msg,
172 ... example.lineno, example.indent, example.options)
173 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
174
175The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000176
Tim Petersbb431472004-08-09 03:51:46 +0000177 Source spans a single line: no terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000178 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000179 >>> e.source, e.want
180 ('print 1\n', '1\n')
181
Edward Lopera6b68322004-08-26 00:05:43 +0000182 >>> e = doctest.Example('print 1\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000183 >>> e.source, e.want
184 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000185
Tim Petersbb431472004-08-09 03:51:46 +0000186 Source spans multiple lines: require terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000187 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000188 >>> e.source, e.want
189 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000190
Edward Lopera6b68322004-08-26 00:05:43 +0000191 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000192 >>> e.source, e.want
193 ('print 1;\nprint 2\n', '1\n2\n')
194
Edward Lopera6b68322004-08-26 00:05:43 +0000195 Empty source string (which should never appear in real examples)
196 >>> e = doctest.Example('', '')
197 >>> e.source, e.want
198 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000199
Edward Lopera6b68322004-08-26 00:05:43 +0000200The constructor normalizes the `want` string to end in a newline,
201unless it's the empty string:
202
203 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000204 >>> e.source, e.want
205 ('print 1\n', '1\n')
206
Edward Lopera6b68322004-08-26 00:05:43 +0000207 >>> e = doctest.Example('print 1', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000208 >>> e.source, e.want
209 ('print 1\n', '1\n')
210
Edward Lopera6b68322004-08-26 00:05:43 +0000211 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000212 >>> e.source, e.want
213 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000214
215The constructor normalizes the `exc_msg` string to end in a newline,
216unless it's `None`:
217
218 Message spans one line
219 >>> exc_msg = 'IndexError: pop from an empty list'
220 >>> e = doctest.Example('[].pop()', '', exc_msg)
221 >>> e.exc_msg
222 'IndexError: pop from an empty list\n'
223
224 >>> exc_msg = 'IndexError: pop from an empty list\n'
225 >>> e = doctest.Example('[].pop()', '', exc_msg)
226 >>> e.exc_msg
227 'IndexError: pop from an empty list\n'
228
229 Message spans multiple lines
230 >>> exc_msg = 'ValueError: 1\n 2'
231 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
232 >>> e.exc_msg
233 'ValueError: 1\n 2\n'
234
235 >>> exc_msg = 'ValueError: 1\n 2\n'
236 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
237 >>> e.exc_msg
238 'ValueError: 1\n 2\n'
239
240 Empty (but non-None) exception message (which should never appear
241 in real examples)
242 >>> exc_msg = ''
243 >>> e = doctest.Example('raise X()', '', exc_msg)
244 >>> e.exc_msg
245 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000246"""
247
248def test_DocTest(): r"""
249Unit tests for the `DocTest` class.
250
251DocTest is a collection of examples, extracted from a docstring, along
252with information about where the docstring comes from (a name,
253filename, and line number). The docstring is parsed by the `DocTest`
254constructor:
255
256 >>> docstring = '''
257 ... >>> print 12
258 ... 12
259 ...
260 ... Non-example text.
261 ...
262 ... >>> print 'another\example'
263 ... another
264 ... example
265 ... '''
266 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000267 >>> parser = doctest.DocTestParser()
268 >>> test = parser.get_doctest(docstring, globs, 'some_test',
269 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000270 >>> print test
271 <DocTest some_test from some_file:20 (2 examples)>
272 >>> len(test.examples)
273 2
274 >>> e1, e2 = test.examples
275 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000276 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000277 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000278 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000279
280Source information (name, filename, and line number) is available as
281attributes on the doctest object:
282
283 >>> (test.name, test.filename, test.lineno)
284 ('some_test', 'some_file', 20)
285
286The line number of an example within its containing file is found by
287adding the line number of the example and the line number of its
288containing test:
289
290 >>> test.lineno + e1.lineno
291 21
292 >>> test.lineno + e2.lineno
293 26
294
295If the docstring contains inconsistant leading whitespace in the
296expected output of an example, then `DocTest` will raise a ValueError:
297
298 >>> docstring = r'''
299 ... >>> print 'bad\nindentation'
300 ... bad
301 ... indentation
302 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000303 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000304 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000305 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000306
307If the docstring contains inconsistent leading whitespace on
308continuation lines, then `DocTest` will raise a ValueError:
309
310 >>> docstring = r'''
311 ... >>> print ('bad indentation',
312 ... ... 2)
313 ... ('bad', 'indentation')
314 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000315 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000316 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000317 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
Tim Peters8485b562004-08-04 18:46:34 +0000318
319If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
320will raise a ValueError:
321
322 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000323 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000324 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000325 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
326
327If there's no blank space after a PS2 prompt ('...'), then `DocTest`
328will raise a ValueError:
329
330 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000331 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000332 Traceback (most recent call last):
333 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
334
Tim Peters8485b562004-08-04 18:46:34 +0000335"""
336
Tim Peters8485b562004-08-04 18:46:34 +0000337def test_DocTestFinder(): r"""
338Unit tests for the `DocTestFinder` class.
339
340DocTestFinder is used to extract DocTests from an object's docstring
341and the docstrings of its contained objects. It can be used with
342modules, functions, classes, methods, staticmethods, classmethods, and
343properties.
344
345Finding Tests in Functions
346~~~~~~~~~~~~~~~~~~~~~~~~~~
347For a function whose docstring contains examples, DocTestFinder.find()
348will return a single test (for that function's docstring):
349
Tim Peters8485b562004-08-04 18:46:34 +0000350 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000351
352We'll simulate a __file__ attr that ends in pyc:
353
354 >>> import test.test_doctest
355 >>> old = test.test_doctest.__file__
356 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
357
Tim Peters8485b562004-08-04 18:46:34 +0000358 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000359
Edward Loper74bca7a2004-08-12 02:27:44 +0000360 >>> print tests # doctest: +ELLIPSIS
Tim Petersa7def722004-08-23 22:13:22 +0000361 [<DocTest sample_func from ...:13 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000362
Tim Peters4de7c5c2004-08-23 22:38:05 +0000363The exact name depends on how test_doctest was invoked, so allow for
364leading path components.
365
366 >>> tests[0].filename # doctest: +ELLIPSIS
367 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000368
369 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000370
Jim Fulton07a349c2004-08-22 14:10:00 +0000371
Tim Peters8485b562004-08-04 18:46:34 +0000372 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000373 >>> (e.source, e.want, e.lineno)
374 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000375
Tim Peters8485b562004-08-04 18:46:34 +0000376If an object has no docstring, then a test is not created for it:
377
378 >>> def no_docstring(v):
379 ... pass
380 >>> finder.find(no_docstring)
381 []
382
383If the function has a docstring with no examples, then a test with no
384examples is returned. (This lets `DocTestRunner` collect statistics
385about which functions have no tests -- but is that useful? And should
386an empty test also be created when there's no docstring?)
387
388 >>> def no_examples(v):
389 ... ''' no doctest examples '''
390 >>> finder.find(no_examples)
391 [<DocTest no_examples from None:1 (no examples)>]
392
393Finding Tests in Classes
394~~~~~~~~~~~~~~~~~~~~~~~~
395For a class, DocTestFinder will create a test for the class's
396docstring, and will recursively explore its contents, including
397methods, classmethods, staticmethods, properties, and nested classes.
398
399 >>> finder = doctest.DocTestFinder()
400 >>> tests = finder.find(SampleClass)
401 >>> tests.sort()
402 >>> for t in tests:
403 ... print '%2s %s' % (len(t.examples), t.name)
404 1 SampleClass
405 3 SampleClass.NestedClass
406 1 SampleClass.NestedClass.__init__
407 1 SampleClass.__init__
408 2 SampleClass.a_classmethod
409 1 SampleClass.a_property
410 1 SampleClass.a_staticmethod
411 1 SampleClass.double
412 1 SampleClass.get
413
414New-style classes are also supported:
415
416 >>> tests = finder.find(SampleNewStyleClass)
417 >>> tests.sort()
418 >>> for t in tests:
419 ... print '%2s %s' % (len(t.examples), t.name)
420 1 SampleNewStyleClass
421 1 SampleNewStyleClass.__init__
422 1 SampleNewStyleClass.double
423 1 SampleNewStyleClass.get
424
425Finding Tests in Modules
426~~~~~~~~~~~~~~~~~~~~~~~~
427For a module, DocTestFinder will create a test for the class's
428docstring, and will recursively explore its contents, including
429functions, classes, and the `__test__` dictionary, if it exists:
430
431 >>> # A module
432 >>> import new
433 >>> m = new.module('some_module')
434 >>> def triple(val):
435 ... '''
436 ... >>> print tripple(11)
437 ... 33
438 ... '''
439 ... return val*3
440 >>> m.__dict__.update({
441 ... 'sample_func': sample_func,
442 ... 'SampleClass': SampleClass,
443 ... '__doc__': '''
444 ... Module docstring.
445 ... >>> print 'module'
446 ... module
447 ... ''',
448 ... '__test__': {
449 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
450 ... 'c': triple}})
451
452 >>> finder = doctest.DocTestFinder()
453 >>> # Use module=test.test_doctest, to prevent doctest from
454 >>> # ignoring the objects since they weren't defined in m.
455 >>> import test.test_doctest
456 >>> tests = finder.find(m, module=test.test_doctest)
457 >>> tests.sort()
458 >>> for t in tests:
459 ... print '%2s %s' % (len(t.examples), t.name)
460 1 some_module
461 1 some_module.SampleClass
462 3 some_module.SampleClass.NestedClass
463 1 some_module.SampleClass.NestedClass.__init__
464 1 some_module.SampleClass.__init__
465 2 some_module.SampleClass.a_classmethod
466 1 some_module.SampleClass.a_property
467 1 some_module.SampleClass.a_staticmethod
468 1 some_module.SampleClass.double
469 1 some_module.SampleClass.get
470 1 some_module.c
471 2 some_module.d
472 1 some_module.sample_func
473
474Duplicate Removal
475~~~~~~~~~~~~~~~~~
476If a single object is listed twice (under different names), then tests
477will only be generated for it once:
478
Tim Petersf3f57472004-08-08 06:11:48 +0000479 >>> from test import doctest_aliases
480 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000481 >>> tests.sort()
482 >>> print len(tests)
483 2
484 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000485 test.doctest_aliases.TwoNames
486
487 TwoNames.f and TwoNames.g are bound to the same object.
488 We can't guess which will be found in doctest's traversal of
489 TwoNames.__dict__ first, so we have to allow for either.
490
491 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000492 True
493
494Filter Functions
495~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000496A filter function can be used to restrict which objects get examined,
497but this is temporary, undocumented internal support for testmod's
498deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000499
500 >>> def namefilter(prefix, base):
501 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000502 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000503 >>> tests.sort()
504 >>> for t in tests:
505 ... print '%2s %s' % (len(t.examples), t.name)
506 1 SampleClass
507 3 SampleClass.NestedClass
508 1 SampleClass.NestedClass.__init__
509 1 SampleClass.__init__
510 1 SampleClass.double
511 1 SampleClass.get
512
Tim Peters8485b562004-08-04 18:46:34 +0000513If a given object is filtered out, then none of the objects that it
514contains will be added either:
515
516 >>> def namefilter(prefix, base):
517 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000518 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000519 >>> tests.sort()
520 >>> for t in tests:
521 ... print '%2s %s' % (len(t.examples), t.name)
522 1 SampleClass
523 1 SampleClass.__init__
524 2 SampleClass.a_classmethod
525 1 SampleClass.a_property
526 1 SampleClass.a_staticmethod
527 1 SampleClass.double
528 1 SampleClass.get
529
Tim Petersf727c6c2004-08-08 01:48:59 +0000530The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000531object explicitly passed to DocTestFinder:
532
533 >>> def namefilter(prefix, base):
534 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000535 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000536 >>> len(tests)
537 9
538
539Turning off Recursion
540~~~~~~~~~~~~~~~~~~~~~
541DocTestFinder can be told not to look for tests in contained objects
542using the `recurse` flag:
543
544 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
545 >>> tests.sort()
546 >>> for t in tests:
547 ... print '%2s %s' % (len(t.examples), t.name)
548 1 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000549
550Line numbers
551~~~~~~~~~~~~
552DocTestFinder finds the line number of each example:
553
554 >>> def f(x):
555 ... '''
556 ... >>> x = 12
557 ...
558 ... some text
559 ...
560 ... >>> # examples are not created for comments & bare prompts.
561 ... >>>
562 ... ...
563 ...
564 ... >>> for x in range(10):
565 ... ... print x,
566 ... 0 1 2 3 4 5 6 7 8 9
567 ... >>> x/2
568 ... 6
569 ... '''
570 >>> test = doctest.DocTestFinder().find(f)[0]
571 >>> [e.lineno for e in test.examples]
572 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000573"""
574
Edward Loper00f8da72004-08-26 18:05:07 +0000575def test_DocTestParser(): r"""
576Unit tests for the `DocTestParser` class.
577
578DocTestParser is used to parse docstrings containing doctest examples.
579
580The `parse` method divides a docstring into examples and intervening
581text:
582
583 >>> s = '''
584 ... >>> x, y = 2, 3 # no output expected
585 ... >>> if 1:
586 ... ... print x
587 ... ... print y
588 ... 2
589 ... 3
590 ...
591 ... Some text.
592 ... >>> x+y
593 ... 5
594 ... '''
595 >>> parser = doctest.DocTestParser()
596 >>> for piece in parser.parse(s):
597 ... if isinstance(piece, doctest.Example):
598 ... print 'Example:', (piece.source, piece.want, piece.lineno)
599 ... else:
600 ... print ' Text:', `piece`
601 Text: '\n'
602 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
603 Text: ''
604 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
605 Text: '\nSome text.\n'
606 Example: ('x+y\n', '5\n', 9)
607 Text: ''
608
609The `get_examples` method returns just the examples:
610
611 >>> for piece in parser.get_examples(s):
612 ... print (piece.source, piece.want, piece.lineno)
613 ('x, y = 2, 3 # no output expected\n', '', 1)
614 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
615 ('x+y\n', '5\n', 9)
616
617The `get_doctest` method creates a Test from the examples, along with the
618given arguments:
619
620 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
621 >>> (test.name, test.filename, test.lineno)
622 ('name', 'filename', 5)
623 >>> for piece in test.examples:
624 ... print (piece.source, piece.want, piece.lineno)
625 ('x, y = 2, 3 # no output expected\n', '', 1)
626 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
627 ('x+y\n', '5\n', 9)
628"""
629
Tim Peters8485b562004-08-04 18:46:34 +0000630class test_DocTestRunner:
631 def basics(): r"""
632Unit tests for the `DocTestRunner` class.
633
634DocTestRunner is used to run DocTest test cases, and to accumulate
635statistics. Here's a simple DocTest case we can use:
636
637 >>> def f(x):
638 ... '''
639 ... >>> x = 12
640 ... >>> print x
641 ... 12
642 ... >>> x/2
643 ... 6
644 ... '''
645 >>> test = doctest.DocTestFinder().find(f)[0]
646
647The main DocTestRunner interface is the `run` method, which runs a
648given DocTest case in a given namespace (globs). It returns a tuple
649`(f,t)`, where `f` is the number of failed tests and `t` is the number
650of tried tests.
651
652 >>> doctest.DocTestRunner(verbose=False).run(test)
653 (0, 3)
654
655If any example produces incorrect output, then the test runner reports
656the failure and proceeds to the next example:
657
658 >>> def f(x):
659 ... '''
660 ... >>> x = 12
661 ... >>> print x
662 ... 14
663 ... >>> x/2
664 ... 6
665 ... '''
666 >>> test = doctest.DocTestFinder().find(f)[0]
667 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000668 Trying:
669 x = 12
670 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000671 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000672 Trying:
673 print x
674 Expecting:
675 14
Tim Peters8485b562004-08-04 18:46:34 +0000676 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000677 Line 3, in f
678 Failed example:
679 print x
680 Expected:
681 14
682 Got:
683 12
Edward Loperaacf0832004-08-26 01:19:50 +0000684 Trying:
685 x/2
686 Expecting:
687 6
Tim Peters8485b562004-08-04 18:46:34 +0000688 ok
689 (1, 3)
690"""
691 def verbose_flag(): r"""
692The `verbose` flag makes the test runner generate more detailed
693output:
694
695 >>> def f(x):
696 ... '''
697 ... >>> x = 12
698 ... >>> print x
699 ... 12
700 ... >>> x/2
701 ... 6
702 ... '''
703 >>> test = doctest.DocTestFinder().find(f)[0]
704
705 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000706 Trying:
707 x = 12
708 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000709 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000710 Trying:
711 print x
712 Expecting:
713 12
Tim Peters8485b562004-08-04 18:46:34 +0000714 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000715 Trying:
716 x/2
717 Expecting:
718 6
Tim Peters8485b562004-08-04 18:46:34 +0000719 ok
720 (0, 3)
721
722If the `verbose` flag is unspecified, then the output will be verbose
723iff `-v` appears in sys.argv:
724
725 >>> # Save the real sys.argv list.
726 >>> old_argv = sys.argv
727
728 >>> # If -v does not appear in sys.argv, then output isn't verbose.
729 >>> sys.argv = ['test']
730 >>> doctest.DocTestRunner().run(test)
731 (0, 3)
732
733 >>> # If -v does appear in sys.argv, then output is verbose.
734 >>> sys.argv = ['test', '-v']
735 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000736 Trying:
737 x = 12
738 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000739 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000740 Trying:
741 print x
742 Expecting:
743 12
Tim Peters8485b562004-08-04 18:46:34 +0000744 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000745 Trying:
746 x/2
747 Expecting:
748 6
Tim Peters8485b562004-08-04 18:46:34 +0000749 ok
750 (0, 3)
751
752 >>> # Restore sys.argv
753 >>> sys.argv = old_argv
754
755In the remaining examples, the test runner's verbosity will be
756explicitly set, to ensure that the test behavior is consistent.
757 """
758 def exceptions(): r"""
759Tests of `DocTestRunner`'s exception handling.
760
761An expected exception is specified with a traceback message. The
762lines between the first line and the type/value may be omitted or
763replaced with any other string:
764
765 >>> def f(x):
766 ... '''
767 ... >>> x = 12
768 ... >>> print x/0
769 ... Traceback (most recent call last):
770 ... ZeroDivisionError: integer division or modulo by zero
771 ... '''
772 >>> test = doctest.DocTestFinder().find(f)[0]
773 >>> doctest.DocTestRunner(verbose=False).run(test)
774 (0, 2)
775
Edward Loper19b19582004-08-25 23:07:03 +0000776An example may not generate output before it raises an exception; if
777it does, then the traceback message will not be recognized as
778signaling an expected exception, so the example will be reported as an
779unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000780
781 >>> def f(x):
782 ... '''
783 ... >>> x = 12
784 ... >>> print 'pre-exception output', x/0
785 ... pre-exception output
786 ... Traceback (most recent call last):
787 ... ZeroDivisionError: integer division or modulo by zero
788 ... '''
789 >>> test = doctest.DocTestFinder().find(f)[0]
790 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000791 ... # doctest: +ELLIPSIS
792 **********************************************************************
793 Line 3, in f
794 Failed example:
795 print 'pre-exception output', x/0
796 Exception raised:
797 ...
798 ZeroDivisionError: integer division or modulo by zero
799 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000800
801Exception messages may contain newlines:
802
803 >>> def f(x):
804 ... r'''
805 ... >>> raise ValueError, 'multi\nline\nmessage'
806 ... Traceback (most recent call last):
807 ... ValueError: multi
808 ... line
809 ... message
810 ... '''
811 >>> test = doctest.DocTestFinder().find(f)[0]
812 >>> doctest.DocTestRunner(verbose=False).run(test)
813 (0, 1)
814
815If an exception is expected, but an exception with the wrong type or
816message is raised, then it is reported as a failure:
817
818 >>> def f(x):
819 ... r'''
820 ... >>> raise ValueError, 'message'
821 ... Traceback (most recent call last):
822 ... ValueError: wrong message
823 ... '''
824 >>> test = doctest.DocTestFinder().find(f)[0]
825 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000826 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000827 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000828 Line 2, in f
829 Failed example:
830 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000831 Expected:
832 Traceback (most recent call last):
833 ValueError: wrong message
834 Got:
835 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000836 ...
Tim Peters8485b562004-08-04 18:46:34 +0000837 ValueError: message
838 (1, 1)
839
Tim Peters1fbf9c52004-09-04 17:21:02 +0000840However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
841detail:
842
843 >>> def f(x):
844 ... r'''
845 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
846 ... Traceback (most recent call last):
847 ... ValueError: wrong message
848 ... '''
849 >>> test = doctest.DocTestFinder().find(f)[0]
850 >>> doctest.DocTestRunner(verbose=False).run(test)
851 (0, 1)
852
853But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
854
855 >>> def f(x):
856 ... r'''
857 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
858 ... Traceback (most recent call last):
859 ... TypeError: wrong type
860 ... '''
861 >>> test = doctest.DocTestFinder().find(f)[0]
862 >>> doctest.DocTestRunner(verbose=False).run(test)
863 ... # doctest: +ELLIPSIS
864 **********************************************************************
865 Line 2, in f
866 Failed example:
867 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
868 Expected:
869 Traceback (most recent call last):
870 TypeError: wrong type
871 Got:
872 Traceback (most recent call last):
873 ...
874 ValueError: message
875 (1, 1)
876
Tim Peters8485b562004-08-04 18:46:34 +0000877If an exception is raised but not expected, then it is reported as an
878unexpected exception:
879
Tim Peters8485b562004-08-04 18:46:34 +0000880 >>> def f(x):
881 ... r'''
882 ... >>> 1/0
883 ... 0
884 ... '''
885 >>> test = doctest.DocTestFinder().find(f)[0]
886 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000887 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000888 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000889 Line 2, in f
890 Failed example:
891 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000892 Exception raised:
893 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000894 ...
Tim Peters8485b562004-08-04 18:46:34 +0000895 ZeroDivisionError: integer division or modulo by zero
896 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000897"""
898 def optionflags(): r"""
899Tests of `DocTestRunner`'s option flag handling.
900
901Several option flags can be used to customize the behavior of the test
902runner. These are defined as module constants in doctest, and passed
903to the DocTestRunner constructor (multiple constants should be or-ed
904together).
905
906The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
907and 1/0:
908
909 >>> def f(x):
910 ... '>>> True\n1\n'
911
912 >>> # Without the flag:
913 >>> test = doctest.DocTestFinder().find(f)[0]
914 >>> doctest.DocTestRunner(verbose=False).run(test)
915 (0, 1)
916
917 >>> # With the flag:
918 >>> test = doctest.DocTestFinder().find(f)[0]
919 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
920 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
921 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000922 Line 1, in f
923 Failed example:
924 True
925 Expected:
926 1
927 Got:
928 True
Tim Peters8485b562004-08-04 18:46:34 +0000929 (1, 1)
930
931The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
932and the '<BLANKLINE>' marker:
933
934 >>> def f(x):
935 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
936
937 >>> # Without the flag:
938 >>> test = doctest.DocTestFinder().find(f)[0]
939 >>> doctest.DocTestRunner(verbose=False).run(test)
940 (0, 1)
941
942 >>> # With the flag:
943 >>> test = doctest.DocTestFinder().find(f)[0]
944 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
945 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
946 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000947 Line 1, in f
948 Failed example:
949 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000950 Expected:
951 a
952 <BLANKLINE>
953 b
954 Got:
955 a
956 <BLANKLINE>
957 b
958 (1, 1)
959
960The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
961treated as equal:
962
963 >>> def f(x):
964 ... '>>> print 1, 2, 3\n 1 2\n 3'
965
966 >>> # Without the flag:
967 >>> test = doctest.DocTestFinder().find(f)[0]
968 >>> doctest.DocTestRunner(verbose=False).run(test)
969 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000970 Line 1, in f
971 Failed example:
972 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000973 Expected:
974 1 2
975 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000976 Got:
977 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000978 (1, 1)
979
980 >>> # With the flag:
981 >>> test = doctest.DocTestFinder().find(f)[0]
982 >>> flags = doctest.NORMALIZE_WHITESPACE
983 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
984 (0, 1)
985
Tim Peters026f8dc2004-08-19 16:38:58 +0000986 An example from the docs:
987 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
988 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
989 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
990
Tim Peters8485b562004-08-04 18:46:34 +0000991The ELLIPSIS flag causes ellipsis marker ("...") in the expected
992output to match any substring in the actual output:
993
994 >>> def f(x):
995 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
996
997 >>> # Without the flag:
998 >>> test = doctest.DocTestFinder().find(f)[0]
999 >>> doctest.DocTestRunner(verbose=False).run(test)
1000 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001001 Line 1, in f
1002 Failed example:
1003 print range(15)
1004 Expected:
1005 [0, 1, 2, ..., 14]
1006 Got:
1007 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +00001008 (1, 1)
1009
1010 >>> # With the flag:
1011 >>> test = doctest.DocTestFinder().find(f)[0]
1012 >>> flags = doctest.ELLIPSIS
1013 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1014 (0, 1)
1015
Tim Peterse594bee2004-08-22 01:47:51 +00001016 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001017
1018 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001019 ... print i**2, #doctest: +ELLIPSIS
1020 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001021
Tim Peters026f8dc2004-08-19 16:38:58 +00001022 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001023
1024 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001025 ... print i,
1026 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001027
Tim Peters026f8dc2004-08-19 16:38:58 +00001028 Examples from the docs:
1029
1030 >>> print range(20) # doctest:+ELLIPSIS
1031 [0, 1, ..., 18, 19]
1032
1033 >>> print range(20) # doctest: +ELLIPSIS
1034 ... # doctest: +NORMALIZE_WHITESPACE
1035 [0, 1, ..., 18, 19]
1036
Edward Loper71f55af2004-08-26 01:41:51 +00001037The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001038and actual outputs to be displayed using a unified diff:
1039
1040 >>> def f(x):
1041 ... r'''
1042 ... >>> print '\n'.join('abcdefg')
1043 ... a
1044 ... B
1045 ... c
1046 ... d
1047 ... f
1048 ... g
1049 ... h
1050 ... '''
1051
1052 >>> # Without the flag:
1053 >>> test = doctest.DocTestFinder().find(f)[0]
1054 >>> doctest.DocTestRunner(verbose=False).run(test)
1055 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001056 Line 2, in f
1057 Failed example:
1058 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001059 Expected:
1060 a
1061 B
1062 c
1063 d
1064 f
1065 g
1066 h
1067 Got:
1068 a
1069 b
1070 c
1071 d
1072 e
1073 f
1074 g
1075 (1, 1)
1076
1077 >>> # With the flag:
1078 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001079 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001080 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1081 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001082 Line 2, in f
1083 Failed example:
1084 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001085 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001086 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001087 a
1088 -B
1089 +b
1090 c
1091 d
1092 +e
1093 f
1094 g
1095 -h
Tim Peters8485b562004-08-04 18:46:34 +00001096 (1, 1)
1097
Edward Loper71f55af2004-08-26 01:41:51 +00001098The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001099and actual outputs to be displayed using a context diff:
1100
Edward Loper71f55af2004-08-26 01:41:51 +00001101 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001102 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001103 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001104 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1105 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001106 Line 2, in f
1107 Failed example:
1108 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001109 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001110 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001111 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001112 a
1113 ! B
1114 c
1115 d
1116 f
1117 g
1118 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001119 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001120 a
1121 ! b
1122 c
1123 d
1124 + e
1125 f
1126 g
Tim Peters8485b562004-08-04 18:46:34 +00001127 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001128
1129
Edward Loper71f55af2004-08-26 01:41:51 +00001130The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001131used by the popular ndiff.py utility. This does intraline difference
1132marking, as well as interline differences.
1133
1134 >>> def f(x):
1135 ... r'''
1136 ... >>> print "a b c d e f g h i j k l m"
1137 ... a b c d e f g h i j k 1 m
1138 ... '''
1139 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001140 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001141 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1142 **********************************************************************
1143 Line 2, in f
1144 Failed example:
1145 print "a b c d e f g h i j k l m"
1146 Differences (ndiff with -expected +actual):
1147 - a b c d e f g h i j k 1 m
1148 ? ^
1149 + a b c d e f g h i j k l m
1150 ? + ++ ^
Tim Petersc6cbab02004-08-22 19:43:28 +00001151 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001152
1153The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1154failing example:
1155
1156 >>> def f(x):
1157 ... r'''
1158 ... >>> print 1 # first success
1159 ... 1
1160 ... >>> print 2 # first failure
1161 ... 200
1162 ... >>> print 3 # second failure
1163 ... 300
1164 ... >>> print 4 # second success
1165 ... 4
1166 ... >>> print 5 # third failure
1167 ... 500
1168 ... '''
1169 >>> test = doctest.DocTestFinder().find(f)[0]
1170 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1171 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1172 **********************************************************************
1173 Line 4, in f
1174 Failed example:
1175 print 2 # first failure
1176 Expected:
1177 200
1178 Got:
1179 2
1180 (3, 5)
1181
1182However, output from `report_start` is not supressed:
1183
1184 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
1185 Trying:
1186 print 1 # first success
1187 Expecting:
1188 1
1189 ok
1190 Trying:
1191 print 2 # first failure
1192 Expecting:
1193 200
1194 **********************************************************************
1195 Line 4, in f
1196 Failed example:
1197 print 2 # first failure
1198 Expected:
1199 200
1200 Got:
1201 2
1202 (3, 5)
1203
1204For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1205count as failures:
1206
1207 >>> def f(x):
1208 ... r'''
1209 ... >>> print 1 # first success
1210 ... 1
1211 ... >>> raise ValueError(2) # first failure
1212 ... 200
1213 ... >>> print 3 # second failure
1214 ... 300
1215 ... >>> print 4 # second success
1216 ... 4
1217 ... >>> print 5 # third failure
1218 ... 500
1219 ... '''
1220 >>> test = doctest.DocTestFinder().find(f)[0]
1221 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1222 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1223 ... # doctest: +ELLIPSIS
1224 **********************************************************************
1225 Line 4, in f
1226 Failed example:
1227 raise ValueError(2) # first failure
1228 Exception raised:
1229 ...
1230 ValueError: 2
1231 (3, 5)
1232
Tim Petersc6cbab02004-08-22 19:43:28 +00001233 """
1234
Tim Peters8485b562004-08-04 18:46:34 +00001235 def option_directives(): r"""
1236Tests of `DocTestRunner`'s option directive mechanism.
1237
Edward Loper74bca7a2004-08-12 02:27:44 +00001238Option directives can be used to turn option flags on or off for a
1239single example. To turn an option on for an example, follow that
1240example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001241
1242 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001243 ... >>> print range(10) # should fail: no ellipsis
1244 ... [0, 1, ..., 9]
1245 ...
1246 ... >>> print range(10) # doctest: +ELLIPSIS
1247 ... [0, 1, ..., 9]
1248 ... '''
1249 >>> test = doctest.DocTestFinder().find(f)[0]
1250 >>> doctest.DocTestRunner(verbose=False).run(test)
1251 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001252 Line 2, in f
1253 Failed example:
1254 print range(10) # should fail: no ellipsis
1255 Expected:
1256 [0, 1, ..., 9]
1257 Got:
1258 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001259 (1, 2)
1260
1261To turn an option off for an example, follow that example with a
1262comment of the form ``# doctest: -OPTION``:
1263
1264 >>> def f(x): r'''
1265 ... >>> print range(10)
1266 ... [0, 1, ..., 9]
1267 ...
1268 ... >>> # should fail: no ellipsis
1269 ... >>> print range(10) # doctest: -ELLIPSIS
1270 ... [0, 1, ..., 9]
1271 ... '''
1272 >>> test = doctest.DocTestFinder().find(f)[0]
1273 >>> doctest.DocTestRunner(verbose=False,
1274 ... optionflags=doctest.ELLIPSIS).run(test)
1275 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001276 Line 6, in f
1277 Failed example:
1278 print range(10) # doctest: -ELLIPSIS
1279 Expected:
1280 [0, 1, ..., 9]
1281 Got:
1282 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001283 (1, 2)
1284
1285Option directives affect only the example that they appear with; they
1286do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001287
Edward Loper74bca7a2004-08-12 02:27:44 +00001288 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001289 ... >>> print range(10) # Should fail: no ellipsis
1290 ... [0, 1, ..., 9]
1291 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001292 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001293 ... [0, 1, ..., 9]
1294 ...
Tim Peters8485b562004-08-04 18:46:34 +00001295 ... >>> print range(10) # Should fail: no ellipsis
1296 ... [0, 1, ..., 9]
1297 ... '''
1298 >>> test = doctest.DocTestFinder().find(f)[0]
1299 >>> doctest.DocTestRunner(verbose=False).run(test)
1300 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001301 Line 2, in f
1302 Failed example:
1303 print range(10) # Should fail: no ellipsis
1304 Expected:
1305 [0, 1, ..., 9]
1306 Got:
1307 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001308 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001309 Line 8, in f
1310 Failed example:
1311 print range(10) # Should fail: no ellipsis
1312 Expected:
1313 [0, 1, ..., 9]
1314 Got:
1315 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001316 (2, 3)
1317
Edward Loper74bca7a2004-08-12 02:27:44 +00001318Multiple options may be modified by a single option directive. They
1319may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001320
1321 >>> def f(x): r'''
1322 ... >>> print range(10) # Should fail
1323 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001324 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001325 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001326 ... [0, 1, ..., 9]
1327 ... '''
1328 >>> test = doctest.DocTestFinder().find(f)[0]
1329 >>> doctest.DocTestRunner(verbose=False).run(test)
1330 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001331 Line 2, in f
1332 Failed example:
1333 print range(10) # Should fail
1334 Expected:
1335 [0, 1, ..., 9]
1336 Got:
1337 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001338 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001339
1340 >>> def f(x): r'''
1341 ... >>> print range(10) # Should fail
1342 ... [0, 1, ..., 9]
1343 ... >>> print range(10) # Should succeed
1344 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1345 ... [0, 1, ..., 9]
1346 ... '''
1347 >>> test = doctest.DocTestFinder().find(f)[0]
1348 >>> doctest.DocTestRunner(verbose=False).run(test)
1349 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001350 Line 2, in f
1351 Failed example:
1352 print range(10) # Should fail
1353 Expected:
1354 [0, 1, ..., 9]
1355 Got:
1356 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001357 (1, 2)
1358
1359 >>> def f(x): r'''
1360 ... >>> print range(10) # Should fail
1361 ... [0, 1, ..., 9]
1362 ... >>> print range(10) # Should succeed
1363 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1364 ... [0, 1, ..., 9]
1365 ... '''
1366 >>> test = doctest.DocTestFinder().find(f)[0]
1367 >>> doctest.DocTestRunner(verbose=False).run(test)
1368 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001369 Line 2, in f
1370 Failed example:
1371 print range(10) # Should fail
1372 Expected:
1373 [0, 1, ..., 9]
1374 Got:
1375 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001376 (1, 2)
1377
1378The option directive may be put on the line following the source, as
1379long as a continuation prompt is used:
1380
1381 >>> def f(x): r'''
1382 ... >>> print range(10)
1383 ... ... # doctest: +ELLIPSIS
1384 ... [0, 1, ..., 9]
1385 ... '''
1386 >>> test = doctest.DocTestFinder().find(f)[0]
1387 >>> doctest.DocTestRunner(verbose=False).run(test)
1388 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001389
Edward Loper74bca7a2004-08-12 02:27:44 +00001390For examples with multi-line source, the option directive may appear
1391at the end of any line:
1392
1393 >>> def f(x): r'''
1394 ... >>> for x in range(10): # doctest: +ELLIPSIS
1395 ... ... print x,
1396 ... 0 1 2 ... 9
1397 ...
1398 ... >>> for x in range(10):
1399 ... ... print x, # doctest: +ELLIPSIS
1400 ... 0 1 2 ... 9
1401 ... '''
1402 >>> test = doctest.DocTestFinder().find(f)[0]
1403 >>> doctest.DocTestRunner(verbose=False).run(test)
1404 (0, 2)
1405
1406If more than one line of an example with multi-line source has an
1407option directive, then they are combined:
1408
1409 >>> def f(x): r'''
1410 ... Should fail (option directive not on the last line):
1411 ... >>> for x in range(10): # doctest: +ELLIPSIS
1412 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1413 ... 0 1 2...9
1414 ... '''
1415 >>> test = doctest.DocTestFinder().find(f)[0]
1416 >>> doctest.DocTestRunner(verbose=False).run(test)
1417 (0, 1)
1418
1419It is an error to have a comment of the form ``# doctest:`` that is
1420*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1421``OPTION`` is an option that has been registered with
1422`register_option`:
1423
1424 >>> # Error: Option not registered
1425 >>> s = '>>> print 12 #doctest: +BADOPTION'
1426 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1427 Traceback (most recent call last):
1428 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1429
1430 >>> # Error: No + or - prefix
1431 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1432 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1433 Traceback (most recent call last):
1434 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1435
1436It is an error to use an option directive on a line that contains no
1437source:
1438
1439 >>> s = '>>> # doctest: +ELLIPSIS'
1440 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1441 Traceback (most recent call last):
1442 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 +00001443"""
1444
1445def test_testsource(): r"""
1446Unit tests for `testsource()`.
1447
1448The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001449test with that name in that module, and converts it to a script. The
1450example code is converted to regular Python code. The surrounding
1451words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001452
1453 >>> import test.test_doctest
1454 >>> name = 'test.test_doctest.sample_func'
1455 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001456 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001457 #
Tim Peters8485b562004-08-04 18:46:34 +00001458 print sample_func(22)
1459 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001460 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001461 #
Edward Lopera5db6002004-08-12 02:41:30 +00001462 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001463
1464 >>> name = 'test.test_doctest.SampleNewStyleClass'
1465 >>> print doctest.testsource(test.test_doctest, name)
1466 print '1\n2\n3'
1467 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001468 ## 1
1469 ## 2
1470 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001471
1472 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1473 >>> print doctest.testsource(test.test_doctest, name)
1474 print SampleClass.a_classmethod(10)
1475 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001476 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001477 print SampleClass(0).a_classmethod(10)
1478 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001479 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001480"""
1481
1482def test_debug(): r"""
1483
1484Create a docstring that we want to debug:
1485
1486 >>> s = '''
1487 ... >>> x = 12
1488 ... >>> print x
1489 ... 12
1490 ... '''
1491
1492Create some fake stdin input, to feed to the debugger:
1493
1494 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001495 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001496 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001497
1498Run the debugger on the docstring, and then restore sys.stdin.
1499
Edward Loper2de91ba2004-08-27 02:07:46 +00001500 >>> try: doctest.debug_src(s)
1501 ... finally: sys.stdin = real_stdin
Tim Peters8485b562004-08-04 18:46:34 +00001502 > <string>(1)?()
Edward Loper2de91ba2004-08-27 02:07:46 +00001503 (Pdb) next
1504 12
Tim Peters8485b562004-08-04 18:46:34 +00001505 --Return--
1506 > <string>(1)?()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001507 (Pdb) print x
1508 12
1509 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001510
1511"""
1512
Jim Fulton356fd192004-08-09 11:34:47 +00001513def test_pdb_set_trace():
Edward Loper2de91ba2004-08-27 02:07:46 +00001514 """Using pdb.set_trace from a doctest
Jim Fulton356fd192004-08-09 11:34:47 +00001515
Tim Peters413ced62004-08-09 15:43:47 +00001516 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001517 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001518 you use it. The doctest module changes sys.stdout so that it can
1519 capture program output. It also temporarily replaces pdb.set_trace
1520 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001521 see debugger output.
1522
1523 >>> doc = '''
1524 ... >>> x = 42
1525 ... >>> import pdb; pdb.set_trace()
1526 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001527 >>> parser = doctest.DocTestParser()
1528 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001529 >>> runner = doctest.DocTestRunner(verbose=False)
1530
1531 To demonstrate this, we'll create a fake standard input that
1532 captures our debugger input:
1533
1534 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001535 >>> real_stdin = sys.stdin
1536 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001537 ... 'print x', # print data defined by the example
1538 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001539 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001540
Edward Loper2de91ba2004-08-27 02:07:46 +00001541 >>> try: runner.run(test)
1542 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001543 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001544 > <doctest foo[1]>(1)?()->None
1545 -> import pdb; pdb.set_trace()
1546 (Pdb) print x
1547 42
1548 (Pdb) continue
1549 (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001550
1551 You can also put pdb.set_trace in a function called from a test:
1552
1553 >>> def calls_set_trace():
1554 ... y=2
1555 ... import pdb; pdb.set_trace()
1556
1557 >>> doc = '''
1558 ... >>> x=1
1559 ... >>> calls_set_trace()
1560 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001561 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001562 >>> real_stdin = sys.stdin
1563 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001564 ... 'print y', # print data defined in the function
1565 ... 'up', # out of function
1566 ... 'print x', # print data defined by the example
1567 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001568 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001569
Edward Loper2de91ba2004-08-27 02:07:46 +00001570 >>> try: runner.run(test)
1571 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001572 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001573 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1574 -> import pdb; pdb.set_trace()
1575 (Pdb) print y
1576 2
1577 (Pdb) up
1578 > <doctest foo[1]>(1)?()
1579 -> calls_set_trace()
1580 (Pdb) print x
1581 1
1582 (Pdb) continue
1583 (0, 2)
1584
1585 During interactive debugging, source code is shown, even for
1586 doctest examples:
1587
1588 >>> doc = '''
1589 ... >>> def f(x):
1590 ... ... g(x*2)
1591 ... >>> def g(x):
1592 ... ... print x+3
1593 ... ... import pdb; pdb.set_trace()
1594 ... >>> f(3)
1595 ... '''
1596 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1597 >>> real_stdin = sys.stdin
1598 >>> sys.stdin = _FakeInput([
1599 ... 'list', # list source from example 2
1600 ... 'next', # return from g()
1601 ... 'list', # list source from example 1
1602 ... 'next', # return from f()
1603 ... 'list', # list source from example 3
1604 ... 'continue', # stop debugging
1605 ... ''])
1606 >>> try: runner.run(test)
1607 ... finally: sys.stdin = real_stdin
1608 ... # doctest: +NORMALIZE_WHITESPACE
1609 --Return--
1610 > <doctest foo[1]>(3)g()->None
1611 -> import pdb; pdb.set_trace()
1612 (Pdb) list
1613 1 def g(x):
1614 2 print x+3
1615 3 -> import pdb; pdb.set_trace()
1616 [EOF]
1617 (Pdb) next
1618 --Return--
1619 > <doctest foo[0]>(2)f()->None
1620 -> g(x*2)
1621 (Pdb) list
1622 1 def f(x):
1623 2 -> g(x*2)
1624 [EOF]
1625 (Pdb) next
1626 --Return--
1627 > <doctest foo[2]>(1)?()->None
1628 -> f(3)
1629 (Pdb) list
1630 1 -> f(3)
1631 [EOF]
1632 (Pdb) continue
1633 **********************************************************************
1634 File "foo.py", line 7, in foo
1635 Failed example:
1636 f(3)
1637 Expected nothing
1638 Got:
1639 9
1640 (1, 3)
Jim Fulton356fd192004-08-09 11:34:47 +00001641 """
1642
Tim Peters19397e52004-08-06 22:02:59 +00001643def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001644 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001645
1646 We create a Suite by providing a module. A module can be provided
1647 by passing a module object:
1648
1649 >>> import unittest
1650 >>> import test.sample_doctest
1651 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1652 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001653 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001654
1655 We can also supply the module by name:
1656
1657 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1658 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001659 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001660
1661 We can use the current module:
1662
1663 >>> suite = test.sample_doctest.test_suite()
1664 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001665 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001666
1667 We can supply global variables. If we pass globs, they will be
1668 used instead of the module globals. Here we'll pass an empty
1669 globals, triggering an extra error:
1670
1671 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1672 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001673 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001674
1675 Alternatively, we can provide extra globals. Here we'll make an
1676 error go away by providing an extra global variable:
1677
1678 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1679 ... extraglobs={'y': 1})
1680 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001681 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001682
1683 You can pass option flags. Here we'll cause an extra error
1684 by disabling the blank-line feature:
1685
1686 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001687 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001688 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001689 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001690
Tim Peters1e277ee2004-08-07 05:37:52 +00001691 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001692
Jim Fultonf54bad42004-08-28 14:57:56 +00001693 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001694 ... import test.test_doctest
1695 ... test.test_doctest.sillySetup = True
1696
Jim Fultonf54bad42004-08-28 14:57:56 +00001697 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001698 ... import test.test_doctest
1699 ... del test.test_doctest.sillySetup
1700
1701 Here, we installed a silly variable that the test expects:
1702
1703 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1704 ... setUp=setUp, tearDown=tearDown)
1705 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001706 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001707
1708 But the tearDown restores sanity:
1709
1710 >>> import test.test_doctest
1711 >>> test.test_doctest.sillySetup
1712 Traceback (most recent call last):
1713 ...
1714 AttributeError: 'module' object has no attribute 'sillySetup'
1715
Jim Fultonf54bad42004-08-28 14:57:56 +00001716 The setUp and tearDown funtions are passed test objects. Here
1717 we'll use the setUp function to supply the missing variable y:
1718
1719 >>> def setUp(test):
1720 ... test.globs['y'] = 1
1721
1722 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1723 >>> suite.run(unittest.TestResult())
1724 <unittest.TestResult run=9 errors=0 failures=3>
1725
1726 Here, we didn't need to use a tearDown function because we
1727 modified the test globals, which are a copy of the
1728 sample_doctest module dictionary. The test globals are
1729 automatically cleared for us after a test.
1730
Tim Peters19397e52004-08-06 22:02:59 +00001731 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001732 use a custom test_finder to to run just the test named bar.
1733 However, the test in the module docstring, and the two tests
1734 in the module __test__ dict, aren't filtered, so we actually
1735 run three tests besides bar's. The filtering mechanisms are
1736 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001737
1738 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001739 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001740 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1741 ... test_finder=finder)
1742 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001743 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001744 """
1745
1746def test_DocFileSuite():
1747 """We can test tests found in text files using a DocFileSuite.
1748
1749 We create a suite by providing the names of one or more text
1750 files that include examples:
1751
1752 >>> import unittest
1753 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1754 ... 'test_doctest2.txt')
1755 >>> suite.run(unittest.TestResult())
1756 <unittest.TestResult run=2 errors=0 failures=2>
1757
1758 The test files are looked for in the directory containing the
1759 calling module. A package keyword argument can be provided to
1760 specify a different relative location.
1761
1762 >>> import unittest
1763 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1764 ... 'test_doctest2.txt',
1765 ... package='test')
1766 >>> suite.run(unittest.TestResult())
1767 <unittest.TestResult run=2 errors=0 failures=2>
1768
1769 Note that '/' should be used as a path separator. It will be
1770 converted to a native separator at run time:
1771
1772
1773 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1774 >>> suite.run(unittest.TestResult())
1775 <unittest.TestResult run=1 errors=0 failures=1>
1776
1777 You can specify initial global variables:
1778
1779 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1780 ... 'test_doctest2.txt',
1781 ... globs={'favorite_color': 'blue'})
1782 >>> suite.run(unittest.TestResult())
1783 <unittest.TestResult run=2 errors=0 failures=1>
1784
1785 In this case, we supplied a missing favorite color. You can
1786 provide doctest options:
1787
1788 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1789 ... 'test_doctest2.txt',
1790 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1791 ... globs={'favorite_color': 'blue'})
1792 >>> suite.run(unittest.TestResult())
1793 <unittest.TestResult run=2 errors=0 failures=2>
1794
1795 And, you can provide setUp and tearDown functions:
1796
1797 You can supply setUp and teatDoen functions:
1798
Jim Fultonf54bad42004-08-28 14:57:56 +00001799 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001800 ... import test.test_doctest
1801 ... test.test_doctest.sillySetup = True
1802
Jim Fultonf54bad42004-08-28 14:57:56 +00001803 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001804 ... import test.test_doctest
1805 ... del test.test_doctest.sillySetup
1806
1807 Here, we installed a silly variable that the test expects:
1808
1809 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1810 ... 'test_doctest2.txt',
1811 ... setUp=setUp, tearDown=tearDown)
1812 >>> suite.run(unittest.TestResult())
1813 <unittest.TestResult run=2 errors=0 failures=1>
1814
1815 But the tearDown restores sanity:
1816
1817 >>> import test.test_doctest
1818 >>> test.test_doctest.sillySetup
1819 Traceback (most recent call last):
1820 ...
1821 AttributeError: 'module' object has no attribute 'sillySetup'
1822
Jim Fultonf54bad42004-08-28 14:57:56 +00001823 The setUp and tearDown funtions are passed test objects.
1824 Here, we'll use a setUp function to set the favorite color in
1825 test_doctest.txt:
1826
1827 >>> def setUp(test):
1828 ... test.globs['favorite_color'] = 'blue'
1829
1830 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
1831 >>> suite.run(unittest.TestResult())
1832 <unittest.TestResult run=1 errors=0 failures=0>
1833
1834 Here, we didn't need to use a tearDown function because we
1835 modified the test globals. The test globals are
1836 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00001837
Jim Fultonf54bad42004-08-28 14:57:56 +00001838 """
Tim Peters19397e52004-08-06 22:02:59 +00001839
Jim Fulton07a349c2004-08-22 14:10:00 +00001840def test_trailing_space_in_test():
1841 """
Tim Petersa7def722004-08-23 22:13:22 +00001842 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001843
Jim Fulton07a349c2004-08-22 14:10:00 +00001844 >>> x, y = 'foo', ''
1845 >>> print x, y
1846 foo \n
1847 """
Tim Peters19397e52004-08-06 22:02:59 +00001848
Jim Fultonf54bad42004-08-28 14:57:56 +00001849
1850def test_unittest_reportflags():
1851 """Default unittest reporting flags can be set to control reporting
1852
1853 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
1854 only the first failure of each test. First, we'll look at the
1855 output without the flag. The file test_doctest.txt file has two
1856 tests. They both fail if blank lines are disabled:
1857
1858 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1859 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
1860 >>> import unittest
1861 >>> result = suite.run(unittest.TestResult())
1862 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1863 Traceback ...
1864 Failed example:
1865 favorite_color
1866 ...
1867 Failed example:
1868 if 1:
1869 ...
1870
1871 Note that we see both failures displayed.
1872
1873 >>> old = doctest.set_unittest_reportflags(
1874 ... doctest.REPORT_ONLY_FIRST_FAILURE)
1875
1876 Now, when we run the test:
1877
1878 >>> result = suite.run(unittest.TestResult())
1879 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1880 Traceback ...
1881 Failed example:
1882 favorite_color
1883 Exception raised:
1884 ...
1885 NameError: name 'favorite_color' is not defined
1886 <BLANKLINE>
1887 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00001888
Jim Fultonf54bad42004-08-28 14:57:56 +00001889 We get only the first failure.
1890
1891 If we give any reporting options when we set up the tests,
1892 however:
1893
1894 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1895 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
1896
1897 Then the default eporting options are ignored:
1898
1899 >>> result = suite.run(unittest.TestResult())
1900 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1901 Traceback ...
1902 Failed example:
1903 favorite_color
1904 ...
1905 Failed example:
1906 if 1:
1907 print 'a'
1908 print
1909 print 'b'
1910 Differences (ndiff with -expected +actual):
1911 a
1912 - <BLANKLINE>
1913 +
1914 b
1915 <BLANKLINE>
1916 <BLANKLINE>
1917
1918
1919 Test runners can restore the formatting flags after they run:
1920
1921 >>> ignored = doctest.set_unittest_reportflags(old)
1922
1923 """
1924
Tim Petersa7def722004-08-23 22:13:22 +00001925# old_test1, ... used to live in doctest.py, but cluttered it. Note
1926# that these use the deprecated doctest.Tester, so should go away (or
1927# be rewritten) someday.
1928
1929# Ignore all warnings about the use of class Tester in this module.
1930# Note that the name of this module may differ depending on how it's
1931# imported, so the use of __name__ is important.
1932warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1933 __name__, 0)
1934
1935def old_test1(): r"""
1936>>> from doctest import Tester
1937>>> t = Tester(globs={'x': 42}, verbose=0)
1938>>> t.runstring(r'''
1939... >>> x = x * 2
1940... >>> print x
1941... 42
1942... ''', 'XYZ')
1943**********************************************************************
1944Line 3, in XYZ
1945Failed example:
1946 print x
1947Expected:
1948 42
1949Got:
1950 84
1951(1, 2)
1952>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1953(0, 2)
1954>>> t.summarize()
1955**********************************************************************
19561 items had failures:
1957 1 of 2 in XYZ
1958***Test Failed*** 1 failures.
1959(1, 4)
1960>>> t.summarize(verbose=1)
19611 items passed all tests:
1962 2 tests in example2
1963**********************************************************************
19641 items had failures:
1965 1 of 2 in XYZ
19664 tests in 2 items.
19673 passed and 1 failed.
1968***Test Failed*** 1 failures.
1969(1, 4)
1970"""
1971
1972def old_test2(): r"""
1973 >>> from doctest import Tester
1974 >>> t = Tester(globs={}, verbose=1)
1975 >>> test = r'''
1976 ... # just an example
1977 ... >>> x = 1 + 2
1978 ... >>> x
1979 ... 3
1980 ... '''
1981 >>> t.runstring(test, "Example")
1982 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00001983 Trying:
1984 x = 1 + 2
1985 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00001986 ok
Edward Loperaacf0832004-08-26 01:19:50 +00001987 Trying:
1988 x
1989 Expecting:
1990 3
Tim Petersa7def722004-08-23 22:13:22 +00001991 ok
1992 0 of 2 examples failed in string Example
1993 (0, 2)
1994"""
1995
1996def old_test3(): r"""
1997 >>> from doctest import Tester
1998 >>> t = Tester(globs={}, verbose=0)
1999 >>> def _f():
2000 ... '''Trivial docstring example.
2001 ... >>> assert 2 == 2
2002 ... '''
2003 ... return 32
2004 ...
2005 >>> t.rundoc(_f) # expect 0 failures in 1 example
2006 (0, 1)
2007"""
2008
2009def old_test4(): """
2010 >>> import new
2011 >>> m1 = new.module('_m1')
2012 >>> m2 = new.module('_m2')
2013 >>> test_data = \"""
2014 ... def _f():
2015 ... '''>>> assert 1 == 1
2016 ... '''
2017 ... def g():
2018 ... '''>>> assert 2 != 1
2019 ... '''
2020 ... class H:
2021 ... '''>>> assert 2 > 1
2022 ... '''
2023 ... def bar(self):
2024 ... '''>>> assert 1 < 2
2025 ... '''
2026 ... \"""
2027 >>> exec test_data in m1.__dict__
2028 >>> exec test_data in m2.__dict__
2029 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2030
2031 Tests that objects outside m1 are excluded:
2032
2033 >>> from doctest import Tester
2034 >>> t = Tester(globs={}, verbose=0)
2035 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
2036 (0, 4)
2037
2038 Once more, not excluding stuff outside m1:
2039
2040 >>> t = Tester(globs={}, verbose=0)
2041 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2042 (0, 8)
2043
2044 The exclusion of objects from outside the designated module is
2045 meant to be invoked automagically by testmod.
2046
2047 >>> doctest.testmod(m1, verbose=False)
2048 (0, 4)
2049"""
2050
Tim Peters8485b562004-08-04 18:46:34 +00002051######################################################################
2052## Main
2053######################################################################
2054
2055def test_main():
2056 # Check the doctest cases in doctest itself:
2057 test_support.run_doctest(doctest, verbosity=True)
2058 # Check the doctest cases defined here:
2059 from test import test_doctest
2060 test_support.run_doctest(test_doctest, verbosity=True)
2061
2062import trace, sys, re, StringIO
2063def test_coverage(coverdir):
2064 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2065 trace=0, count=1)
2066 tracer.run('reload(doctest); test_main()')
2067 r = tracer.results()
2068 print 'Writing coverage results...'
2069 r.write_results(show_missing=True, summary=True,
2070 coverdir=coverdir)
2071
2072if __name__ == '__main__':
2073 if '-c' in sys.argv:
2074 test_coverage('/tmp/doctest.cover')
2075 else:
2076 test_main()