blob: 53798ab74965181973e232a1d79367c353e3c4c2 [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
840If an exception is raised but not expected, then it is reported as an
841unexpected exception:
842
Tim Peters8485b562004-08-04 18:46:34 +0000843 >>> def f(x):
844 ... r'''
845 ... >>> 1/0
846 ... 0
847 ... '''
848 >>> test = doctest.DocTestFinder().find(f)[0]
849 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000850 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000851 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000852 Line 2, in f
853 Failed example:
854 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000855 Exception raised:
856 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000857 ...
Tim Peters8485b562004-08-04 18:46:34 +0000858 ZeroDivisionError: integer division or modulo by zero
859 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000860"""
861 def optionflags(): r"""
862Tests of `DocTestRunner`'s option flag handling.
863
864Several option flags can be used to customize the behavior of the test
865runner. These are defined as module constants in doctest, and passed
866to the DocTestRunner constructor (multiple constants should be or-ed
867together).
868
869The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
870and 1/0:
871
872 >>> def f(x):
873 ... '>>> True\n1\n'
874
875 >>> # Without the flag:
876 >>> test = doctest.DocTestFinder().find(f)[0]
877 >>> doctest.DocTestRunner(verbose=False).run(test)
878 (0, 1)
879
880 >>> # With the flag:
881 >>> test = doctest.DocTestFinder().find(f)[0]
882 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
883 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
884 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000885 Line 1, in f
886 Failed example:
887 True
888 Expected:
889 1
890 Got:
891 True
Tim Peters8485b562004-08-04 18:46:34 +0000892 (1, 1)
893
894The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
895and the '<BLANKLINE>' marker:
896
897 >>> def f(x):
898 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
899
900 >>> # Without the flag:
901 >>> test = doctest.DocTestFinder().find(f)[0]
902 >>> doctest.DocTestRunner(verbose=False).run(test)
903 (0, 1)
904
905 >>> # With the flag:
906 >>> test = doctest.DocTestFinder().find(f)[0]
907 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
908 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
909 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000910 Line 1, in f
911 Failed example:
912 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000913 Expected:
914 a
915 <BLANKLINE>
916 b
917 Got:
918 a
919 <BLANKLINE>
920 b
921 (1, 1)
922
923The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
924treated as equal:
925
926 >>> def f(x):
927 ... '>>> print 1, 2, 3\n 1 2\n 3'
928
929 >>> # Without the flag:
930 >>> test = doctest.DocTestFinder().find(f)[0]
931 >>> doctest.DocTestRunner(verbose=False).run(test)
932 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000933 Line 1, in f
934 Failed example:
935 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000936 Expected:
937 1 2
938 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000939 Got:
940 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000941 (1, 1)
942
943 >>> # With the flag:
944 >>> test = doctest.DocTestFinder().find(f)[0]
945 >>> flags = doctest.NORMALIZE_WHITESPACE
946 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
947 (0, 1)
948
Tim Peters026f8dc2004-08-19 16:38:58 +0000949 An example from the docs:
950 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
951 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
952 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
953
Tim Peters8485b562004-08-04 18:46:34 +0000954The ELLIPSIS flag causes ellipsis marker ("...") in the expected
955output to match any substring in the actual output:
956
957 >>> def f(x):
958 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
959
960 >>> # Without the flag:
961 >>> test = doctest.DocTestFinder().find(f)[0]
962 >>> doctest.DocTestRunner(verbose=False).run(test)
963 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000964 Line 1, in f
965 Failed example:
966 print range(15)
967 Expected:
968 [0, 1, 2, ..., 14]
969 Got:
970 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +0000971 (1, 1)
972
973 >>> # With the flag:
974 >>> test = doctest.DocTestFinder().find(f)[0]
975 >>> flags = doctest.ELLIPSIS
976 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
977 (0, 1)
978
Tim Peterse594bee2004-08-22 01:47:51 +0000979 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +0000980
981 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +0000982 ... print i**2, #doctest: +ELLIPSIS
983 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +0000984
Tim Peters026f8dc2004-08-19 16:38:58 +0000985 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000986
987 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +0000988 ... print i,
989 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +0000990
Tim Peters026f8dc2004-08-19 16:38:58 +0000991 Examples from the docs:
992
993 >>> print range(20) # doctest:+ELLIPSIS
994 [0, 1, ..., 18, 19]
995
996 >>> print range(20) # doctest: +ELLIPSIS
997 ... # doctest: +NORMALIZE_WHITESPACE
998 [0, 1, ..., 18, 19]
999
Edward Loper71f55af2004-08-26 01:41:51 +00001000The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001001and actual outputs to be displayed using a unified diff:
1002
1003 >>> def f(x):
1004 ... r'''
1005 ... >>> print '\n'.join('abcdefg')
1006 ... a
1007 ... B
1008 ... c
1009 ... d
1010 ... f
1011 ... g
1012 ... h
1013 ... '''
1014
1015 >>> # Without the flag:
1016 >>> test = doctest.DocTestFinder().find(f)[0]
1017 >>> doctest.DocTestRunner(verbose=False).run(test)
1018 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001019 Line 2, in f
1020 Failed example:
1021 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001022 Expected:
1023 a
1024 B
1025 c
1026 d
1027 f
1028 g
1029 h
1030 Got:
1031 a
1032 b
1033 c
1034 d
1035 e
1036 f
1037 g
1038 (1, 1)
1039
1040 >>> # With the flag:
1041 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001042 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001043 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1044 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001045 Line 2, in f
1046 Failed example:
1047 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001048 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001049 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001050 a
1051 -B
1052 +b
1053 c
1054 d
1055 +e
1056 f
1057 g
1058 -h
Tim Peters8485b562004-08-04 18:46:34 +00001059 (1, 1)
1060
Edward Loper71f55af2004-08-26 01:41:51 +00001061The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001062and actual outputs to be displayed using a context diff:
1063
Edward Loper71f55af2004-08-26 01:41:51 +00001064 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001065 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001066 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001067 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1068 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001069 Line 2, in f
1070 Failed example:
1071 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001072 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001073 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001074 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001075 a
1076 ! B
1077 c
1078 d
1079 f
1080 g
1081 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001082 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001083 a
1084 ! b
1085 c
1086 d
1087 + e
1088 f
1089 g
Tim Peters8485b562004-08-04 18:46:34 +00001090 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001091
1092
Edward Loper71f55af2004-08-26 01:41:51 +00001093The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001094used by the popular ndiff.py utility. This does intraline difference
1095marking, as well as interline differences.
1096
1097 >>> def f(x):
1098 ... r'''
1099 ... >>> print "a b c d e f g h i j k l m"
1100 ... a b c d e f g h i j k 1 m
1101 ... '''
1102 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001103 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001104 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1105 **********************************************************************
1106 Line 2, in f
1107 Failed example:
1108 print "a b c d e f g h i j k l m"
1109 Differences (ndiff with -expected +actual):
1110 - a b c d e f g h i j k 1 m
1111 ? ^
1112 + a b c d e f g h i j k l m
1113 ? + ++ ^
Tim Petersc6cbab02004-08-22 19:43:28 +00001114 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001115
1116The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1117failing example:
1118
1119 >>> def f(x):
1120 ... r'''
1121 ... >>> print 1 # first success
1122 ... 1
1123 ... >>> print 2 # first failure
1124 ... 200
1125 ... >>> print 3 # second failure
1126 ... 300
1127 ... >>> print 4 # second success
1128 ... 4
1129 ... >>> print 5 # third failure
1130 ... 500
1131 ... '''
1132 >>> test = doctest.DocTestFinder().find(f)[0]
1133 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1134 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1135 **********************************************************************
1136 Line 4, in f
1137 Failed example:
1138 print 2 # first failure
1139 Expected:
1140 200
1141 Got:
1142 2
1143 (3, 5)
1144
1145However, output from `report_start` is not supressed:
1146
1147 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
1148 Trying:
1149 print 1 # first success
1150 Expecting:
1151 1
1152 ok
1153 Trying:
1154 print 2 # first failure
1155 Expecting:
1156 200
1157 **********************************************************************
1158 Line 4, in f
1159 Failed example:
1160 print 2 # first failure
1161 Expected:
1162 200
1163 Got:
1164 2
1165 (3, 5)
1166
1167For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1168count as failures:
1169
1170 >>> def f(x):
1171 ... r'''
1172 ... >>> print 1 # first success
1173 ... 1
1174 ... >>> raise ValueError(2) # first failure
1175 ... 200
1176 ... >>> print 3 # second failure
1177 ... 300
1178 ... >>> print 4 # second success
1179 ... 4
1180 ... >>> print 5 # third failure
1181 ... 500
1182 ... '''
1183 >>> test = doctest.DocTestFinder().find(f)[0]
1184 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1185 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1186 ... # doctest: +ELLIPSIS
1187 **********************************************************************
1188 Line 4, in f
1189 Failed example:
1190 raise ValueError(2) # first failure
1191 Exception raised:
1192 ...
1193 ValueError: 2
1194 (3, 5)
1195
Tim Petersc6cbab02004-08-22 19:43:28 +00001196 """
1197
Tim Peters8485b562004-08-04 18:46:34 +00001198 def option_directives(): r"""
1199Tests of `DocTestRunner`'s option directive mechanism.
1200
Edward Loper74bca7a2004-08-12 02:27:44 +00001201Option directives can be used to turn option flags on or off for a
1202single example. To turn an option on for an example, follow that
1203example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001204
1205 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001206 ... >>> print range(10) # should fail: no ellipsis
1207 ... [0, 1, ..., 9]
1208 ...
1209 ... >>> print range(10) # doctest: +ELLIPSIS
1210 ... [0, 1, ..., 9]
1211 ... '''
1212 >>> test = doctest.DocTestFinder().find(f)[0]
1213 >>> doctest.DocTestRunner(verbose=False).run(test)
1214 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001215 Line 2, in f
1216 Failed example:
1217 print range(10) # should fail: no ellipsis
1218 Expected:
1219 [0, 1, ..., 9]
1220 Got:
1221 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001222 (1, 2)
1223
1224To turn an option off for an example, follow that example with a
1225comment of the form ``# doctest: -OPTION``:
1226
1227 >>> def f(x): r'''
1228 ... >>> print range(10)
1229 ... [0, 1, ..., 9]
1230 ...
1231 ... >>> # should fail: no ellipsis
1232 ... >>> print range(10) # doctest: -ELLIPSIS
1233 ... [0, 1, ..., 9]
1234 ... '''
1235 >>> test = doctest.DocTestFinder().find(f)[0]
1236 >>> doctest.DocTestRunner(verbose=False,
1237 ... optionflags=doctest.ELLIPSIS).run(test)
1238 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001239 Line 6, in f
1240 Failed example:
1241 print range(10) # doctest: -ELLIPSIS
1242 Expected:
1243 [0, 1, ..., 9]
1244 Got:
1245 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001246 (1, 2)
1247
1248Option directives affect only the example that they appear with; they
1249do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001250
Edward Loper74bca7a2004-08-12 02:27:44 +00001251 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001252 ... >>> print range(10) # Should fail: no ellipsis
1253 ... [0, 1, ..., 9]
1254 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001255 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001256 ... [0, 1, ..., 9]
1257 ...
Tim Peters8485b562004-08-04 18:46:34 +00001258 ... >>> print range(10) # Should fail: no ellipsis
1259 ... [0, 1, ..., 9]
1260 ... '''
1261 >>> test = doctest.DocTestFinder().find(f)[0]
1262 >>> doctest.DocTestRunner(verbose=False).run(test)
1263 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001264 Line 2, in f
1265 Failed example:
1266 print range(10) # Should fail: no ellipsis
1267 Expected:
1268 [0, 1, ..., 9]
1269 Got:
1270 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001271 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001272 Line 8, in f
1273 Failed example:
1274 print range(10) # Should fail: no ellipsis
1275 Expected:
1276 [0, 1, ..., 9]
1277 Got:
1278 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001279 (2, 3)
1280
Edward Loper74bca7a2004-08-12 02:27:44 +00001281Multiple options may be modified by a single option directive. They
1282may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001283
1284 >>> def f(x): r'''
1285 ... >>> print range(10) # Should fail
1286 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001287 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001288 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001289 ... [0, 1, ..., 9]
1290 ... '''
1291 >>> test = doctest.DocTestFinder().find(f)[0]
1292 >>> doctest.DocTestRunner(verbose=False).run(test)
1293 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001294 Line 2, in f
1295 Failed example:
1296 print range(10) # Should fail
1297 Expected:
1298 [0, 1, ..., 9]
1299 Got:
1300 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001301 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001302
1303 >>> def f(x): r'''
1304 ... >>> print range(10) # Should fail
1305 ... [0, 1, ..., 9]
1306 ... >>> print range(10) # Should succeed
1307 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1308 ... [0, 1, ..., 9]
1309 ... '''
1310 >>> test = doctest.DocTestFinder().find(f)[0]
1311 >>> doctest.DocTestRunner(verbose=False).run(test)
1312 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001313 Line 2, in f
1314 Failed example:
1315 print range(10) # Should fail
1316 Expected:
1317 [0, 1, ..., 9]
1318 Got:
1319 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001320 (1, 2)
1321
1322 >>> def f(x): r'''
1323 ... >>> print range(10) # Should fail
1324 ... [0, 1, ..., 9]
1325 ... >>> print range(10) # Should succeed
1326 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1327 ... [0, 1, ..., 9]
1328 ... '''
1329 >>> test = doctest.DocTestFinder().find(f)[0]
1330 >>> doctest.DocTestRunner(verbose=False).run(test)
1331 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001332 Line 2, in f
1333 Failed example:
1334 print range(10) # Should fail
1335 Expected:
1336 [0, 1, ..., 9]
1337 Got:
1338 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001339 (1, 2)
1340
1341The option directive may be put on the line following the source, as
1342long as a continuation prompt is used:
1343
1344 >>> def f(x): r'''
1345 ... >>> print range(10)
1346 ... ... # doctest: +ELLIPSIS
1347 ... [0, 1, ..., 9]
1348 ... '''
1349 >>> test = doctest.DocTestFinder().find(f)[0]
1350 >>> doctest.DocTestRunner(verbose=False).run(test)
1351 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001352
Edward Loper74bca7a2004-08-12 02:27:44 +00001353For examples with multi-line source, the option directive may appear
1354at the end of any line:
1355
1356 >>> def f(x): r'''
1357 ... >>> for x in range(10): # doctest: +ELLIPSIS
1358 ... ... print x,
1359 ... 0 1 2 ... 9
1360 ...
1361 ... >>> for x in range(10):
1362 ... ... print x, # doctest: +ELLIPSIS
1363 ... 0 1 2 ... 9
1364 ... '''
1365 >>> test = doctest.DocTestFinder().find(f)[0]
1366 >>> doctest.DocTestRunner(verbose=False).run(test)
1367 (0, 2)
1368
1369If more than one line of an example with multi-line source has an
1370option directive, then they are combined:
1371
1372 >>> def f(x): r'''
1373 ... Should fail (option directive not on the last line):
1374 ... >>> for x in range(10): # doctest: +ELLIPSIS
1375 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1376 ... 0 1 2...9
1377 ... '''
1378 >>> test = doctest.DocTestFinder().find(f)[0]
1379 >>> doctest.DocTestRunner(verbose=False).run(test)
1380 (0, 1)
1381
1382It is an error to have a comment of the form ``# doctest:`` that is
1383*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1384``OPTION`` is an option that has been registered with
1385`register_option`:
1386
1387 >>> # Error: Option not registered
1388 >>> s = '>>> print 12 #doctest: +BADOPTION'
1389 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1390 Traceback (most recent call last):
1391 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1392
1393 >>> # Error: No + or - prefix
1394 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1395 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1396 Traceback (most recent call last):
1397 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1398
1399It is an error to use an option directive on a line that contains no
1400source:
1401
1402 >>> s = '>>> # doctest: +ELLIPSIS'
1403 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1404 Traceback (most recent call last):
1405 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 +00001406"""
1407
1408def test_testsource(): r"""
1409Unit tests for `testsource()`.
1410
1411The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001412test with that name in that module, and converts it to a script. The
1413example code is converted to regular Python code. The surrounding
1414words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001415
1416 >>> import test.test_doctest
1417 >>> name = 'test.test_doctest.sample_func'
1418 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001419 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001420 #
Tim Peters8485b562004-08-04 18:46:34 +00001421 print sample_func(22)
1422 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001423 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001424 #
Edward Lopera5db6002004-08-12 02:41:30 +00001425 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001426
1427 >>> name = 'test.test_doctest.SampleNewStyleClass'
1428 >>> print doctest.testsource(test.test_doctest, name)
1429 print '1\n2\n3'
1430 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001431 ## 1
1432 ## 2
1433 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001434
1435 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1436 >>> print doctest.testsource(test.test_doctest, name)
1437 print SampleClass.a_classmethod(10)
1438 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001439 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001440 print SampleClass(0).a_classmethod(10)
1441 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001442 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001443"""
1444
1445def test_debug(): r"""
1446
1447Create a docstring that we want to debug:
1448
1449 >>> s = '''
1450 ... >>> x = 12
1451 ... >>> print x
1452 ... 12
1453 ... '''
1454
1455Create some fake stdin input, to feed to the debugger:
1456
1457 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001458 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001459 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001460
1461Run the debugger on the docstring, and then restore sys.stdin.
1462
Edward Loper2de91ba2004-08-27 02:07:46 +00001463 >>> try: doctest.debug_src(s)
1464 ... finally: sys.stdin = real_stdin
Tim Peters8485b562004-08-04 18:46:34 +00001465 > <string>(1)?()
Edward Loper2de91ba2004-08-27 02:07:46 +00001466 (Pdb) next
1467 12
Tim Peters8485b562004-08-04 18:46:34 +00001468 --Return--
1469 > <string>(1)?()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001470 (Pdb) print x
1471 12
1472 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001473
1474"""
1475
Jim Fulton356fd192004-08-09 11:34:47 +00001476def test_pdb_set_trace():
Edward Loper2de91ba2004-08-27 02:07:46 +00001477 """Using pdb.set_trace from a doctest
Jim Fulton356fd192004-08-09 11:34:47 +00001478
Tim Peters413ced62004-08-09 15:43:47 +00001479 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001480 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001481 you use it. The doctest module changes sys.stdout so that it can
1482 capture program output. It also temporarily replaces pdb.set_trace
1483 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001484 see debugger output.
1485
1486 >>> doc = '''
1487 ... >>> x = 42
1488 ... >>> import pdb; pdb.set_trace()
1489 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001490 >>> parser = doctest.DocTestParser()
1491 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001492 >>> runner = doctest.DocTestRunner(verbose=False)
1493
1494 To demonstrate this, we'll create a fake standard input that
1495 captures our debugger input:
1496
1497 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001498 >>> real_stdin = sys.stdin
1499 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001500 ... 'print x', # print data defined by the example
1501 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001502 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001503
Edward Loper2de91ba2004-08-27 02:07:46 +00001504 >>> try: runner.run(test)
1505 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001506 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001507 > <doctest foo[1]>(1)?()->None
1508 -> import pdb; pdb.set_trace()
1509 (Pdb) print x
1510 42
1511 (Pdb) continue
1512 (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001513
1514 You can also put pdb.set_trace in a function called from a test:
1515
1516 >>> def calls_set_trace():
1517 ... y=2
1518 ... import pdb; pdb.set_trace()
1519
1520 >>> doc = '''
1521 ... >>> x=1
1522 ... >>> calls_set_trace()
1523 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001524 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001525 >>> real_stdin = sys.stdin
1526 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001527 ... 'print y', # print data defined in the function
1528 ... 'up', # out of function
1529 ... 'print x', # print data defined by the example
1530 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001531 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001532
Edward Loper2de91ba2004-08-27 02:07:46 +00001533 >>> try: runner.run(test)
1534 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001535 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001536 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1537 -> import pdb; pdb.set_trace()
1538 (Pdb) print y
1539 2
1540 (Pdb) up
1541 > <doctest foo[1]>(1)?()
1542 -> calls_set_trace()
1543 (Pdb) print x
1544 1
1545 (Pdb) continue
1546 (0, 2)
1547
1548 During interactive debugging, source code is shown, even for
1549 doctest examples:
1550
1551 >>> doc = '''
1552 ... >>> def f(x):
1553 ... ... g(x*2)
1554 ... >>> def g(x):
1555 ... ... print x+3
1556 ... ... import pdb; pdb.set_trace()
1557 ... >>> f(3)
1558 ... '''
1559 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1560 >>> real_stdin = sys.stdin
1561 >>> sys.stdin = _FakeInput([
1562 ... 'list', # list source from example 2
1563 ... 'next', # return from g()
1564 ... 'list', # list source from example 1
1565 ... 'next', # return from f()
1566 ... 'list', # list source from example 3
1567 ... 'continue', # stop debugging
1568 ... ''])
1569 >>> try: runner.run(test)
1570 ... finally: sys.stdin = real_stdin
1571 ... # doctest: +NORMALIZE_WHITESPACE
1572 --Return--
1573 > <doctest foo[1]>(3)g()->None
1574 -> import pdb; pdb.set_trace()
1575 (Pdb) list
1576 1 def g(x):
1577 2 print x+3
1578 3 -> import pdb; pdb.set_trace()
1579 [EOF]
1580 (Pdb) next
1581 --Return--
1582 > <doctest foo[0]>(2)f()->None
1583 -> g(x*2)
1584 (Pdb) list
1585 1 def f(x):
1586 2 -> g(x*2)
1587 [EOF]
1588 (Pdb) next
1589 --Return--
1590 > <doctest foo[2]>(1)?()->None
1591 -> f(3)
1592 (Pdb) list
1593 1 -> f(3)
1594 [EOF]
1595 (Pdb) continue
1596 **********************************************************************
1597 File "foo.py", line 7, in foo
1598 Failed example:
1599 f(3)
1600 Expected nothing
1601 Got:
1602 9
1603 (1, 3)
Jim Fulton356fd192004-08-09 11:34:47 +00001604 """
1605
Tim Peters19397e52004-08-06 22:02:59 +00001606def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001607 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001608
1609 We create a Suite by providing a module. A module can be provided
1610 by passing a module object:
1611
1612 >>> import unittest
1613 >>> import test.sample_doctest
1614 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1615 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001616 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001617
1618 We can also supply the module by name:
1619
1620 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1621 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001622 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001623
1624 We can use the current module:
1625
1626 >>> suite = test.sample_doctest.test_suite()
1627 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001628 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001629
1630 We can supply global variables. If we pass globs, they will be
1631 used instead of the module globals. Here we'll pass an empty
1632 globals, triggering an extra error:
1633
1634 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1635 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001636 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001637
1638 Alternatively, we can provide extra globals. Here we'll make an
1639 error go away by providing an extra global variable:
1640
1641 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1642 ... extraglobs={'y': 1})
1643 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001644 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001645
1646 You can pass option flags. Here we'll cause an extra error
1647 by disabling the blank-line feature:
1648
1649 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001650 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001651 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001652 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001653
Tim Peters1e277ee2004-08-07 05:37:52 +00001654 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001655
Jim Fultonf54bad42004-08-28 14:57:56 +00001656 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001657 ... import test.test_doctest
1658 ... test.test_doctest.sillySetup = True
1659
Jim Fultonf54bad42004-08-28 14:57:56 +00001660 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001661 ... import test.test_doctest
1662 ... del test.test_doctest.sillySetup
1663
1664 Here, we installed a silly variable that the test expects:
1665
1666 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1667 ... setUp=setUp, tearDown=tearDown)
1668 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001669 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001670
1671 But the tearDown restores sanity:
1672
1673 >>> import test.test_doctest
1674 >>> test.test_doctest.sillySetup
1675 Traceback (most recent call last):
1676 ...
1677 AttributeError: 'module' object has no attribute 'sillySetup'
1678
Jim Fultonf54bad42004-08-28 14:57:56 +00001679 The setUp and tearDown funtions are passed test objects. Here
1680 we'll use the setUp function to supply the missing variable y:
1681
1682 >>> def setUp(test):
1683 ... test.globs['y'] = 1
1684
1685 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1686 >>> suite.run(unittest.TestResult())
1687 <unittest.TestResult run=9 errors=0 failures=3>
1688
1689 Here, we didn't need to use a tearDown function because we
1690 modified the test globals, which are a copy of the
1691 sample_doctest module dictionary. The test globals are
1692 automatically cleared for us after a test.
1693
Tim Peters19397e52004-08-06 22:02:59 +00001694 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001695 use a custom test_finder to to run just the test named bar.
1696 However, the test in the module docstring, and the two tests
1697 in the module __test__ dict, aren't filtered, so we actually
1698 run three tests besides bar's. The filtering mechanisms are
1699 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001700
1701 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001702 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001703 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1704 ... test_finder=finder)
1705 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001706 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001707 """
1708
1709def test_DocFileSuite():
1710 """We can test tests found in text files using a DocFileSuite.
1711
1712 We create a suite by providing the names of one or more text
1713 files that include examples:
1714
1715 >>> import unittest
1716 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1717 ... 'test_doctest2.txt')
1718 >>> suite.run(unittest.TestResult())
1719 <unittest.TestResult run=2 errors=0 failures=2>
1720
1721 The test files are looked for in the directory containing the
1722 calling module. A package keyword argument can be provided to
1723 specify a different relative location.
1724
1725 >>> import unittest
1726 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1727 ... 'test_doctest2.txt',
1728 ... package='test')
1729 >>> suite.run(unittest.TestResult())
1730 <unittest.TestResult run=2 errors=0 failures=2>
1731
1732 Note that '/' should be used as a path separator. It will be
1733 converted to a native separator at run time:
1734
1735
1736 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1737 >>> suite.run(unittest.TestResult())
1738 <unittest.TestResult run=1 errors=0 failures=1>
1739
1740 You can specify initial global variables:
1741
1742 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1743 ... 'test_doctest2.txt',
1744 ... globs={'favorite_color': 'blue'})
1745 >>> suite.run(unittest.TestResult())
1746 <unittest.TestResult run=2 errors=0 failures=1>
1747
1748 In this case, we supplied a missing favorite color. You can
1749 provide doctest options:
1750
1751 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1752 ... 'test_doctest2.txt',
1753 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1754 ... globs={'favorite_color': 'blue'})
1755 >>> suite.run(unittest.TestResult())
1756 <unittest.TestResult run=2 errors=0 failures=2>
1757
1758 And, you can provide setUp and tearDown functions:
1759
1760 You can supply setUp and teatDoen functions:
1761
Jim Fultonf54bad42004-08-28 14:57:56 +00001762 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001763 ... import test.test_doctest
1764 ... test.test_doctest.sillySetup = True
1765
Jim Fultonf54bad42004-08-28 14:57:56 +00001766 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001767 ... import test.test_doctest
1768 ... del test.test_doctest.sillySetup
1769
1770 Here, we installed a silly variable that the test expects:
1771
1772 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1773 ... 'test_doctest2.txt',
1774 ... setUp=setUp, tearDown=tearDown)
1775 >>> suite.run(unittest.TestResult())
1776 <unittest.TestResult run=2 errors=0 failures=1>
1777
1778 But the tearDown restores sanity:
1779
1780 >>> import test.test_doctest
1781 >>> test.test_doctest.sillySetup
1782 Traceback (most recent call last):
1783 ...
1784 AttributeError: 'module' object has no attribute 'sillySetup'
1785
Jim Fultonf54bad42004-08-28 14:57:56 +00001786 The setUp and tearDown funtions are passed test objects.
1787 Here, we'll use a setUp function to set the favorite color in
1788 test_doctest.txt:
1789
1790 >>> def setUp(test):
1791 ... test.globs['favorite_color'] = 'blue'
1792
1793 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
1794 >>> suite.run(unittest.TestResult())
1795 <unittest.TestResult run=1 errors=0 failures=0>
1796
1797 Here, we didn't need to use a tearDown function because we
1798 modified the test globals. The test globals are
1799 automatically cleared for us after a test.
1800
1801 """
Tim Peters19397e52004-08-06 22:02:59 +00001802
Jim Fulton07a349c2004-08-22 14:10:00 +00001803def test_trailing_space_in_test():
1804 """
Tim Petersa7def722004-08-23 22:13:22 +00001805 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001806
Jim Fulton07a349c2004-08-22 14:10:00 +00001807 >>> x, y = 'foo', ''
1808 >>> print x, y
1809 foo \n
1810 """
Tim Peters19397e52004-08-06 22:02:59 +00001811
Jim Fultonf54bad42004-08-28 14:57:56 +00001812
1813def test_unittest_reportflags():
1814 """Default unittest reporting flags can be set to control reporting
1815
1816 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
1817 only the first failure of each test. First, we'll look at the
1818 output without the flag. The file test_doctest.txt file has two
1819 tests. They both fail if blank lines are disabled:
1820
1821 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1822 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
1823 >>> import unittest
1824 >>> result = suite.run(unittest.TestResult())
1825 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1826 Traceback ...
1827 Failed example:
1828 favorite_color
1829 ...
1830 Failed example:
1831 if 1:
1832 ...
1833
1834 Note that we see both failures displayed.
1835
1836 >>> old = doctest.set_unittest_reportflags(
1837 ... doctest.REPORT_ONLY_FIRST_FAILURE)
1838
1839 Now, when we run the test:
1840
1841 >>> result = suite.run(unittest.TestResult())
1842 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1843 Traceback ...
1844 Failed example:
1845 favorite_color
1846 Exception raised:
1847 ...
1848 NameError: name 'favorite_color' is not defined
1849 <BLANKLINE>
1850 <BLANKLINE>
1851
1852 We get only the first failure.
1853
1854 If we give any reporting options when we set up the tests,
1855 however:
1856
1857 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1858 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
1859
1860 Then the default eporting options are ignored:
1861
1862 >>> result = suite.run(unittest.TestResult())
1863 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1864 Traceback ...
1865 Failed example:
1866 favorite_color
1867 ...
1868 Failed example:
1869 if 1:
1870 print 'a'
1871 print
1872 print 'b'
1873 Differences (ndiff with -expected +actual):
1874 a
1875 - <BLANKLINE>
1876 +
1877 b
1878 <BLANKLINE>
1879 <BLANKLINE>
1880
1881
1882 Test runners can restore the formatting flags after they run:
1883
1884 >>> ignored = doctest.set_unittest_reportflags(old)
1885
1886 """
1887
Tim Petersa7def722004-08-23 22:13:22 +00001888# old_test1, ... used to live in doctest.py, but cluttered it. Note
1889# that these use the deprecated doctest.Tester, so should go away (or
1890# be rewritten) someday.
1891
1892# Ignore all warnings about the use of class Tester in this module.
1893# Note that the name of this module may differ depending on how it's
1894# imported, so the use of __name__ is important.
1895warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1896 __name__, 0)
1897
1898def old_test1(): r"""
1899>>> from doctest import Tester
1900>>> t = Tester(globs={'x': 42}, verbose=0)
1901>>> t.runstring(r'''
1902... >>> x = x * 2
1903... >>> print x
1904... 42
1905... ''', 'XYZ')
1906**********************************************************************
1907Line 3, in XYZ
1908Failed example:
1909 print x
1910Expected:
1911 42
1912Got:
1913 84
1914(1, 2)
1915>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1916(0, 2)
1917>>> t.summarize()
1918**********************************************************************
19191 items had failures:
1920 1 of 2 in XYZ
1921***Test Failed*** 1 failures.
1922(1, 4)
1923>>> t.summarize(verbose=1)
19241 items passed all tests:
1925 2 tests in example2
1926**********************************************************************
19271 items had failures:
1928 1 of 2 in XYZ
19294 tests in 2 items.
19303 passed and 1 failed.
1931***Test Failed*** 1 failures.
1932(1, 4)
1933"""
1934
1935def old_test2(): r"""
1936 >>> from doctest import Tester
1937 >>> t = Tester(globs={}, verbose=1)
1938 >>> test = r'''
1939 ... # just an example
1940 ... >>> x = 1 + 2
1941 ... >>> x
1942 ... 3
1943 ... '''
1944 >>> t.runstring(test, "Example")
1945 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00001946 Trying:
1947 x = 1 + 2
1948 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00001949 ok
Edward Loperaacf0832004-08-26 01:19:50 +00001950 Trying:
1951 x
1952 Expecting:
1953 3
Tim Petersa7def722004-08-23 22:13:22 +00001954 ok
1955 0 of 2 examples failed in string Example
1956 (0, 2)
1957"""
1958
1959def old_test3(): r"""
1960 >>> from doctest import Tester
1961 >>> t = Tester(globs={}, verbose=0)
1962 >>> def _f():
1963 ... '''Trivial docstring example.
1964 ... >>> assert 2 == 2
1965 ... '''
1966 ... return 32
1967 ...
1968 >>> t.rundoc(_f) # expect 0 failures in 1 example
1969 (0, 1)
1970"""
1971
1972def old_test4(): """
1973 >>> import new
1974 >>> m1 = new.module('_m1')
1975 >>> m2 = new.module('_m2')
1976 >>> test_data = \"""
1977 ... def _f():
1978 ... '''>>> assert 1 == 1
1979 ... '''
1980 ... def g():
1981 ... '''>>> assert 2 != 1
1982 ... '''
1983 ... class H:
1984 ... '''>>> assert 2 > 1
1985 ... '''
1986 ... def bar(self):
1987 ... '''>>> assert 1 < 2
1988 ... '''
1989 ... \"""
1990 >>> exec test_data in m1.__dict__
1991 >>> exec test_data in m2.__dict__
1992 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
1993
1994 Tests that objects outside m1 are excluded:
1995
1996 >>> from doctest import Tester
1997 >>> t = Tester(globs={}, verbose=0)
1998 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
1999 (0, 4)
2000
2001 Once more, not excluding stuff outside m1:
2002
2003 >>> t = Tester(globs={}, verbose=0)
2004 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2005 (0, 8)
2006
2007 The exclusion of objects from outside the designated module is
2008 meant to be invoked automagically by testmod.
2009
2010 >>> doctest.testmod(m1, verbose=False)
2011 (0, 4)
2012"""
2013
Tim Peters8485b562004-08-04 18:46:34 +00002014######################################################################
2015## Main
2016######################################################################
2017
2018def test_main():
2019 # Check the doctest cases in doctest itself:
2020 test_support.run_doctest(doctest, verbosity=True)
2021 # Check the doctest cases defined here:
2022 from test import test_doctest
2023 test_support.run_doctest(test_doctest, verbosity=True)
2024
2025import trace, sys, re, StringIO
2026def test_coverage(coverdir):
2027 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2028 trace=0, count=1)
2029 tracer.run('reload(doctest); test_main()')
2030 r = tracer.results()
2031 print 'Writing coverage results...'
2032 r.write_results(show_missing=True, summary=True,
2033 coverdir=coverdir)
2034
2035if __name__ == '__main__':
2036 if '-c' in sys.argv:
2037 test_coverage('/tmp/doctest.cover')
2038 else:
2039 test_main()