blob: 7884c045dd23dc371279dff2c97a0d1f39b13864 [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######################################################################
120## Test Cases
121######################################################################
122
123def test_Example(): r"""
124Unit tests for the `Example` class.
125
Edward Lopera6b68322004-08-26 00:05:43 +0000126Example is a simple container class that holds:
127 - `source`: A source string.
128 - `want`: An expected output string.
129 - `exc_msg`: An expected exception message string (or None if no
130 exception is expected).
131 - `lineno`: A line number (within the docstring).
132 - `indent`: The example's indentation in the input string.
133 - `options`: An option dictionary, mapping option flags to True or
134 False.
Tim Peters8485b562004-08-04 18:46:34 +0000135
Edward Lopera6b68322004-08-26 00:05:43 +0000136These attributes are set by the constructor. `source` and `want` are
137required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000138
Edward Lopera6b68322004-08-26 00:05:43 +0000139 >>> example = doctest.Example('print 1', '1\n')
140 >>> (example.source, example.want, example.exc_msg,
141 ... example.lineno, example.indent, example.options)
142 ('print 1\n', '1\n', None, 0, 0, {})
143
144The first three attributes (`source`, `want`, and `exc_msg`) may be
145specified positionally; the remaining arguments should be specified as
146keyword arguments:
147
148 >>> exc_msg = 'IndexError: pop from an empty list'
149 >>> example = doctest.Example('[].pop()', '', exc_msg,
150 ... lineno=5, indent=4,
151 ... options={doctest.ELLIPSIS: True})
152 >>> (example.source, example.want, example.exc_msg,
153 ... example.lineno, example.indent, example.options)
154 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
155
156The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000157
Tim Petersbb431472004-08-09 03:51:46 +0000158 Source spans a single line: no terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000159 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000160 >>> e.source, e.want
161 ('print 1\n', '1\n')
162
Edward Lopera6b68322004-08-26 00:05:43 +0000163 >>> e = doctest.Example('print 1\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000164 >>> e.source, e.want
165 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000166
Tim Petersbb431472004-08-09 03:51:46 +0000167 Source spans multiple lines: require terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000168 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000169 >>> e.source, e.want
170 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000171
Edward Lopera6b68322004-08-26 00:05:43 +0000172 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000173 >>> e.source, e.want
174 ('print 1;\nprint 2\n', '1\n2\n')
175
Edward Lopera6b68322004-08-26 00:05:43 +0000176 Empty source string (which should never appear in real examples)
177 >>> e = doctest.Example('', '')
178 >>> e.source, e.want
179 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000180
Edward Lopera6b68322004-08-26 00:05:43 +0000181The constructor normalizes the `want` string to end in a newline,
182unless it's the empty string:
183
184 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000185 >>> e.source, e.want
186 ('print 1\n', '1\n')
187
Edward Lopera6b68322004-08-26 00:05:43 +0000188 >>> e = doctest.Example('print 1', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000189 >>> e.source, e.want
190 ('print 1\n', '1\n')
191
Edward Lopera6b68322004-08-26 00:05:43 +0000192 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000193 >>> e.source, e.want
194 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000195
196The constructor normalizes the `exc_msg` string to end in a newline,
197unless it's `None`:
198
199 Message spans one line
200 >>> exc_msg = 'IndexError: pop from an empty list'
201 >>> e = doctest.Example('[].pop()', '', exc_msg)
202 >>> e.exc_msg
203 'IndexError: pop from an empty list\n'
204
205 >>> exc_msg = 'IndexError: pop from an empty list\n'
206 >>> e = doctest.Example('[].pop()', '', exc_msg)
207 >>> e.exc_msg
208 'IndexError: pop from an empty list\n'
209
210 Message spans multiple lines
211 >>> exc_msg = 'ValueError: 1\n 2'
212 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
213 >>> e.exc_msg
214 'ValueError: 1\n 2\n'
215
216 >>> exc_msg = 'ValueError: 1\n 2\n'
217 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
218 >>> e.exc_msg
219 'ValueError: 1\n 2\n'
220
221 Empty (but non-None) exception message (which should never appear
222 in real examples)
223 >>> exc_msg = ''
224 >>> e = doctest.Example('raise X()', '', exc_msg)
225 >>> e.exc_msg
226 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000227"""
228
229def test_DocTest(): r"""
230Unit tests for the `DocTest` class.
231
232DocTest is a collection of examples, extracted from a docstring, along
233with information about where the docstring comes from (a name,
234filename, and line number). The docstring is parsed by the `DocTest`
235constructor:
236
237 >>> docstring = '''
238 ... >>> print 12
239 ... 12
240 ...
241 ... Non-example text.
242 ...
243 ... >>> print 'another\example'
244 ... another
245 ... example
246 ... '''
247 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000248 >>> parser = doctest.DocTestParser()
249 >>> test = parser.get_doctest(docstring, globs, 'some_test',
250 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000251 >>> print test
252 <DocTest some_test from some_file:20 (2 examples)>
253 >>> len(test.examples)
254 2
255 >>> e1, e2 = test.examples
256 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000257 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000258 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000259 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000260
261Source information (name, filename, and line number) is available as
262attributes on the doctest object:
263
264 >>> (test.name, test.filename, test.lineno)
265 ('some_test', 'some_file', 20)
266
267The line number of an example within its containing file is found by
268adding the line number of the example and the line number of its
269containing test:
270
271 >>> test.lineno + e1.lineno
272 21
273 >>> test.lineno + e2.lineno
274 26
275
276If the docstring contains inconsistant leading whitespace in the
277expected output of an example, then `DocTest` will raise a ValueError:
278
279 >>> docstring = r'''
280 ... >>> print 'bad\nindentation'
281 ... bad
282 ... indentation
283 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000284 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000285 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000286 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: ' indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000287
288If the docstring contains inconsistent leading whitespace on
289continuation lines, then `DocTest` will raise a ValueError:
290
291 >>> docstring = r'''
292 ... >>> print ('bad indentation',
293 ... ... 2)
294 ... ('bad', 'indentation')
295 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000296 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000297 Traceback (most recent call last):
298 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: ' ... 2)'
299
300If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
301will raise a ValueError:
302
303 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000304 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000305 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000306 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
307
308If there's no blank space after a PS2 prompt ('...'), then `DocTest`
309will raise a ValueError:
310
311 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000312 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000313 Traceback (most recent call last):
314 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
315
Tim Peters8485b562004-08-04 18:46:34 +0000316"""
317
Tim Peters8485b562004-08-04 18:46:34 +0000318def test_DocTestFinder(): r"""
319Unit tests for the `DocTestFinder` class.
320
321DocTestFinder is used to extract DocTests from an object's docstring
322and the docstrings of its contained objects. It can be used with
323modules, functions, classes, methods, staticmethods, classmethods, and
324properties.
325
326Finding Tests in Functions
327~~~~~~~~~~~~~~~~~~~~~~~~~~
328For a function whose docstring contains examples, DocTestFinder.find()
329will return a single test (for that function's docstring):
330
Tim Peters8485b562004-08-04 18:46:34 +0000331 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000332
333We'll simulate a __file__ attr that ends in pyc:
334
335 >>> import test.test_doctest
336 >>> old = test.test_doctest.__file__
337 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
338
Tim Peters8485b562004-08-04 18:46:34 +0000339 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000340
Edward Loper74bca7a2004-08-12 02:27:44 +0000341 >>> print tests # doctest: +ELLIPSIS
Tim Petersa7def722004-08-23 22:13:22 +0000342 [<DocTest sample_func from ...:13 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000343
Tim Peters4de7c5c2004-08-23 22:38:05 +0000344The exact name depends on how test_doctest was invoked, so allow for
345leading path components.
346
347 >>> tests[0].filename # doctest: +ELLIPSIS
348 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000349
350 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000351
Jim Fulton07a349c2004-08-22 14:10:00 +0000352
Tim Peters8485b562004-08-04 18:46:34 +0000353 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000354 >>> (e.source, e.want, e.lineno)
355 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000356
Tim Peters8485b562004-08-04 18:46:34 +0000357If an object has no docstring, then a test is not created for it:
358
359 >>> def no_docstring(v):
360 ... pass
361 >>> finder.find(no_docstring)
362 []
363
364If the function has a docstring with no examples, then a test with no
365examples is returned. (This lets `DocTestRunner` collect statistics
366about which functions have no tests -- but is that useful? And should
367an empty test also be created when there's no docstring?)
368
369 >>> def no_examples(v):
370 ... ''' no doctest examples '''
371 >>> finder.find(no_examples)
372 [<DocTest no_examples from None:1 (no examples)>]
373
374Finding Tests in Classes
375~~~~~~~~~~~~~~~~~~~~~~~~
376For a class, DocTestFinder will create a test for the class's
377docstring, and will recursively explore its contents, including
378methods, classmethods, staticmethods, properties, and nested classes.
379
380 >>> finder = doctest.DocTestFinder()
381 >>> tests = finder.find(SampleClass)
382 >>> tests.sort()
383 >>> for t in tests:
384 ... print '%2s %s' % (len(t.examples), t.name)
385 1 SampleClass
386 3 SampleClass.NestedClass
387 1 SampleClass.NestedClass.__init__
388 1 SampleClass.__init__
389 2 SampleClass.a_classmethod
390 1 SampleClass.a_property
391 1 SampleClass.a_staticmethod
392 1 SampleClass.double
393 1 SampleClass.get
394
395New-style classes are also supported:
396
397 >>> tests = finder.find(SampleNewStyleClass)
398 >>> tests.sort()
399 >>> for t in tests:
400 ... print '%2s %s' % (len(t.examples), t.name)
401 1 SampleNewStyleClass
402 1 SampleNewStyleClass.__init__
403 1 SampleNewStyleClass.double
404 1 SampleNewStyleClass.get
405
406Finding Tests in Modules
407~~~~~~~~~~~~~~~~~~~~~~~~
408For a module, DocTestFinder will create a test for the class's
409docstring, and will recursively explore its contents, including
410functions, classes, and the `__test__` dictionary, if it exists:
411
412 >>> # A module
413 >>> import new
414 >>> m = new.module('some_module')
415 >>> def triple(val):
416 ... '''
417 ... >>> print tripple(11)
418 ... 33
419 ... '''
420 ... return val*3
421 >>> m.__dict__.update({
422 ... 'sample_func': sample_func,
423 ... 'SampleClass': SampleClass,
424 ... '__doc__': '''
425 ... Module docstring.
426 ... >>> print 'module'
427 ... module
428 ... ''',
429 ... '__test__': {
430 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
431 ... 'c': triple}})
432
433 >>> finder = doctest.DocTestFinder()
434 >>> # Use module=test.test_doctest, to prevent doctest from
435 >>> # ignoring the objects since they weren't defined in m.
436 >>> import test.test_doctest
437 >>> tests = finder.find(m, module=test.test_doctest)
438 >>> tests.sort()
439 >>> for t in tests:
440 ... print '%2s %s' % (len(t.examples), t.name)
441 1 some_module
442 1 some_module.SampleClass
443 3 some_module.SampleClass.NestedClass
444 1 some_module.SampleClass.NestedClass.__init__
445 1 some_module.SampleClass.__init__
446 2 some_module.SampleClass.a_classmethod
447 1 some_module.SampleClass.a_property
448 1 some_module.SampleClass.a_staticmethod
449 1 some_module.SampleClass.double
450 1 some_module.SampleClass.get
451 1 some_module.c
452 2 some_module.d
453 1 some_module.sample_func
454
455Duplicate Removal
456~~~~~~~~~~~~~~~~~
457If a single object is listed twice (under different names), then tests
458will only be generated for it once:
459
Tim Petersf3f57472004-08-08 06:11:48 +0000460 >>> from test import doctest_aliases
461 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000462 >>> tests.sort()
463 >>> print len(tests)
464 2
465 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000466 test.doctest_aliases.TwoNames
467
468 TwoNames.f and TwoNames.g are bound to the same object.
469 We can't guess which will be found in doctest's traversal of
470 TwoNames.__dict__ first, so we have to allow for either.
471
472 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000473 True
474
475Filter Functions
476~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000477A filter function can be used to restrict which objects get examined,
478but this is temporary, undocumented internal support for testmod's
479deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000480
481 >>> def namefilter(prefix, base):
482 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000483 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000484 >>> tests.sort()
485 >>> for t in tests:
486 ... print '%2s %s' % (len(t.examples), t.name)
487 1 SampleClass
488 3 SampleClass.NestedClass
489 1 SampleClass.NestedClass.__init__
490 1 SampleClass.__init__
491 1 SampleClass.double
492 1 SampleClass.get
493
Tim Peters8485b562004-08-04 18:46:34 +0000494If a given object is filtered out, then none of the objects that it
495contains will be added either:
496
497 >>> def namefilter(prefix, base):
498 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000499 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000500 >>> tests.sort()
501 >>> for t in tests:
502 ... print '%2s %s' % (len(t.examples), t.name)
503 1 SampleClass
504 1 SampleClass.__init__
505 2 SampleClass.a_classmethod
506 1 SampleClass.a_property
507 1 SampleClass.a_staticmethod
508 1 SampleClass.double
509 1 SampleClass.get
510
Tim Petersf727c6c2004-08-08 01:48:59 +0000511The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000512object explicitly passed to DocTestFinder:
513
514 >>> def namefilter(prefix, base):
515 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000516 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000517 >>> len(tests)
518 9
519
520Turning off Recursion
521~~~~~~~~~~~~~~~~~~~~~
522DocTestFinder can be told not to look for tests in contained objects
523using the `recurse` flag:
524
525 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
526 >>> tests.sort()
527 >>> for t in tests:
528 ... print '%2s %s' % (len(t.examples), t.name)
529 1 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000530
531Line numbers
532~~~~~~~~~~~~
533DocTestFinder finds the line number of each example:
534
535 >>> def f(x):
536 ... '''
537 ... >>> x = 12
538 ...
539 ... some text
540 ...
541 ... >>> # examples are not created for comments & bare prompts.
542 ... >>>
543 ... ...
544 ...
545 ... >>> for x in range(10):
546 ... ... print x,
547 ... 0 1 2 3 4 5 6 7 8 9
548 ... >>> x/2
549 ... 6
550 ... '''
551 >>> test = doctest.DocTestFinder().find(f)[0]
552 >>> [e.lineno for e in test.examples]
553 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000554"""
555
556class test_DocTestRunner:
557 def basics(): r"""
558Unit tests for the `DocTestRunner` class.
559
560DocTestRunner is used to run DocTest test cases, and to accumulate
561statistics. Here's a simple DocTest case we can use:
562
563 >>> def f(x):
564 ... '''
565 ... >>> x = 12
566 ... >>> print x
567 ... 12
568 ... >>> x/2
569 ... 6
570 ... '''
571 >>> test = doctest.DocTestFinder().find(f)[0]
572
573The main DocTestRunner interface is the `run` method, which runs a
574given DocTest case in a given namespace (globs). It returns a tuple
575`(f,t)`, where `f` is the number of failed tests and `t` is the number
576of tried tests.
577
578 >>> doctest.DocTestRunner(verbose=False).run(test)
579 (0, 3)
580
581If any example produces incorrect output, then the test runner reports
582the failure and proceeds to the next example:
583
584 >>> def f(x):
585 ... '''
586 ... >>> x = 12
587 ... >>> print x
588 ... 14
589 ... >>> x/2
590 ... 6
591 ... '''
592 >>> test = doctest.DocTestFinder().find(f)[0]
593 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000594 Trying:
595 x = 12
596 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000597 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000598 Trying:
599 print x
600 Expecting:
601 14
Tim Peters8485b562004-08-04 18:46:34 +0000602 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000603 Line 3, in f
604 Failed example:
605 print x
606 Expected:
607 14
608 Got:
609 12
Edward Loperaacf0832004-08-26 01:19:50 +0000610 Trying:
611 x/2
612 Expecting:
613 6
Tim Peters8485b562004-08-04 18:46:34 +0000614 ok
615 (1, 3)
616"""
617 def verbose_flag(): r"""
618The `verbose` flag makes the test runner generate more detailed
619output:
620
621 >>> def f(x):
622 ... '''
623 ... >>> x = 12
624 ... >>> print x
625 ... 12
626 ... >>> x/2
627 ... 6
628 ... '''
629 >>> test = doctest.DocTestFinder().find(f)[0]
630
631 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000632 Trying:
633 x = 12
634 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000635 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000636 Trying:
637 print x
638 Expecting:
639 12
Tim Peters8485b562004-08-04 18:46:34 +0000640 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000641 Trying:
642 x/2
643 Expecting:
644 6
Tim Peters8485b562004-08-04 18:46:34 +0000645 ok
646 (0, 3)
647
648If the `verbose` flag is unspecified, then the output will be verbose
649iff `-v` appears in sys.argv:
650
651 >>> # Save the real sys.argv list.
652 >>> old_argv = sys.argv
653
654 >>> # If -v does not appear in sys.argv, then output isn't verbose.
655 >>> sys.argv = ['test']
656 >>> doctest.DocTestRunner().run(test)
657 (0, 3)
658
659 >>> # If -v does appear in sys.argv, then output is verbose.
660 >>> sys.argv = ['test', '-v']
661 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000662 Trying:
663 x = 12
664 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000665 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000666 Trying:
667 print x
668 Expecting:
669 12
Tim Peters8485b562004-08-04 18:46:34 +0000670 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000671 Trying:
672 x/2
673 Expecting:
674 6
Tim Peters8485b562004-08-04 18:46:34 +0000675 ok
676 (0, 3)
677
678 >>> # Restore sys.argv
679 >>> sys.argv = old_argv
680
681In the remaining examples, the test runner's verbosity will be
682explicitly set, to ensure that the test behavior is consistent.
683 """
684 def exceptions(): r"""
685Tests of `DocTestRunner`'s exception handling.
686
687An expected exception is specified with a traceback message. The
688lines between the first line and the type/value may be omitted or
689replaced with any other string:
690
691 >>> def f(x):
692 ... '''
693 ... >>> x = 12
694 ... >>> print x/0
695 ... Traceback (most recent call last):
696 ... ZeroDivisionError: integer division or modulo by zero
697 ... '''
698 >>> test = doctest.DocTestFinder().find(f)[0]
699 >>> doctest.DocTestRunner(verbose=False).run(test)
700 (0, 2)
701
Edward Loper19b19582004-08-25 23:07:03 +0000702An example may not generate output before it raises an exception; if
703it does, then the traceback message will not be recognized as
704signaling an expected exception, so the example will be reported as an
705unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000706
707 >>> def f(x):
708 ... '''
709 ... >>> x = 12
710 ... >>> print 'pre-exception output', x/0
711 ... pre-exception output
712 ... Traceback (most recent call last):
713 ... ZeroDivisionError: integer division or modulo by zero
714 ... '''
715 >>> test = doctest.DocTestFinder().find(f)[0]
716 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000717 ... # doctest: +ELLIPSIS
718 **********************************************************************
719 Line 3, in f
720 Failed example:
721 print 'pre-exception output', x/0
722 Exception raised:
723 ...
724 ZeroDivisionError: integer division or modulo by zero
725 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000726
727Exception messages may contain newlines:
728
729 >>> def f(x):
730 ... r'''
731 ... >>> raise ValueError, 'multi\nline\nmessage'
732 ... Traceback (most recent call last):
733 ... ValueError: multi
734 ... line
735 ... message
736 ... '''
737 >>> test = doctest.DocTestFinder().find(f)[0]
738 >>> doctest.DocTestRunner(verbose=False).run(test)
739 (0, 1)
740
741If an exception is expected, but an exception with the wrong type or
742message is raised, then it is reported as a failure:
743
744 >>> def f(x):
745 ... r'''
746 ... >>> raise ValueError, 'message'
747 ... Traceback (most recent call last):
748 ... ValueError: wrong message
749 ... '''
750 >>> test = doctest.DocTestFinder().find(f)[0]
751 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000752 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000753 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000754 Line 2, in f
755 Failed example:
756 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000757 Expected:
758 Traceback (most recent call last):
759 ValueError: wrong message
760 Got:
761 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000762 ...
Tim Peters8485b562004-08-04 18:46:34 +0000763 ValueError: message
764 (1, 1)
765
766If an exception is raised but not expected, then it is reported as an
767unexpected exception:
768
Tim Peters8485b562004-08-04 18:46:34 +0000769 >>> def f(x):
770 ... r'''
771 ... >>> 1/0
772 ... 0
773 ... '''
774 >>> test = doctest.DocTestFinder().find(f)[0]
775 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000776 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000777 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000778 Line 2, in f
779 Failed example:
780 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000781 Exception raised:
782 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000783 ...
Tim Peters8485b562004-08-04 18:46:34 +0000784 ZeroDivisionError: integer division or modulo by zero
785 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000786"""
787 def optionflags(): r"""
788Tests of `DocTestRunner`'s option flag handling.
789
790Several option flags can be used to customize the behavior of the test
791runner. These are defined as module constants in doctest, and passed
792to the DocTestRunner constructor (multiple constants should be or-ed
793together).
794
795The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
796and 1/0:
797
798 >>> def f(x):
799 ... '>>> True\n1\n'
800
801 >>> # Without the flag:
802 >>> test = doctest.DocTestFinder().find(f)[0]
803 >>> doctest.DocTestRunner(verbose=False).run(test)
804 (0, 1)
805
806 >>> # With the flag:
807 >>> test = doctest.DocTestFinder().find(f)[0]
808 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
809 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
810 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000811 Line 1, in f
812 Failed example:
813 True
814 Expected:
815 1
816 Got:
817 True
Tim Peters8485b562004-08-04 18:46:34 +0000818 (1, 1)
819
820The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
821and the '<BLANKLINE>' marker:
822
823 >>> def f(x):
824 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
825
826 >>> # Without the flag:
827 >>> test = doctest.DocTestFinder().find(f)[0]
828 >>> doctest.DocTestRunner(verbose=False).run(test)
829 (0, 1)
830
831 >>> # With the flag:
832 >>> test = doctest.DocTestFinder().find(f)[0]
833 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
834 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
835 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000836 Line 1, in f
837 Failed example:
838 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000839 Expected:
840 a
841 <BLANKLINE>
842 b
843 Got:
844 a
845 <BLANKLINE>
846 b
847 (1, 1)
848
849The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
850treated as equal:
851
852 >>> def f(x):
853 ... '>>> print 1, 2, 3\n 1 2\n 3'
854
855 >>> # Without the flag:
856 >>> test = doctest.DocTestFinder().find(f)[0]
857 >>> doctest.DocTestRunner(verbose=False).run(test)
858 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000859 Line 1, in f
860 Failed example:
861 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000862 Expected:
863 1 2
864 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000865 Got:
866 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000867 (1, 1)
868
869 >>> # With the flag:
870 >>> test = doctest.DocTestFinder().find(f)[0]
871 >>> flags = doctest.NORMALIZE_WHITESPACE
872 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
873 (0, 1)
874
Tim Peters026f8dc2004-08-19 16:38:58 +0000875 An example from the docs:
876 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
877 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
878 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
879
Tim Peters8485b562004-08-04 18:46:34 +0000880The ELLIPSIS flag causes ellipsis marker ("...") in the expected
881output to match any substring in the actual output:
882
883 >>> def f(x):
884 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
885
886 >>> # Without the flag:
887 >>> test = doctest.DocTestFinder().find(f)[0]
888 >>> doctest.DocTestRunner(verbose=False).run(test)
889 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000890 Line 1, in f
891 Failed example:
892 print range(15)
893 Expected:
894 [0, 1, 2, ..., 14]
895 Got:
896 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +0000897 (1, 1)
898
899 >>> # With the flag:
900 >>> test = doctest.DocTestFinder().find(f)[0]
901 >>> flags = doctest.ELLIPSIS
902 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
903 (0, 1)
904
Tim Peterse594bee2004-08-22 01:47:51 +0000905 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +0000906
907 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +0000908 ... print i**2, #doctest: +ELLIPSIS
909 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +0000910
Tim Peters026f8dc2004-08-19 16:38:58 +0000911 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000912
913 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +0000914 ... print i,
915 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +0000916
Tim Peters026f8dc2004-08-19 16:38:58 +0000917 Examples from the docs:
918
919 >>> print range(20) # doctest:+ELLIPSIS
920 [0, 1, ..., 18, 19]
921
922 >>> print range(20) # doctest: +ELLIPSIS
923 ... # doctest: +NORMALIZE_WHITESPACE
924 [0, 1, ..., 18, 19]
925
Tim Peters8485b562004-08-04 18:46:34 +0000926The UNIFIED_DIFF flag causes failures that involve multi-line expected
927and actual outputs to be displayed using a unified diff:
928
929 >>> def f(x):
930 ... r'''
931 ... >>> print '\n'.join('abcdefg')
932 ... a
933 ... B
934 ... c
935 ... d
936 ... f
937 ... g
938 ... h
939 ... '''
940
941 >>> # Without the flag:
942 >>> test = doctest.DocTestFinder().find(f)[0]
943 >>> doctest.DocTestRunner(verbose=False).run(test)
944 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000945 Line 2, in f
946 Failed example:
947 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000948 Expected:
949 a
950 B
951 c
952 d
953 f
954 g
955 h
956 Got:
957 a
958 b
959 c
960 d
961 e
962 f
963 g
964 (1, 1)
965
966 >>> # With the flag:
967 >>> test = doctest.DocTestFinder().find(f)[0]
968 >>> flags = doctest.UNIFIED_DIFF
969 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
970 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000971 Line 2, in f
972 Failed example:
973 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000974 Differences (unified diff):
975 --- Expected
976 +++ Got
977 @@ -1,8 +1,8 @@
978 a
979 -B
980 +b
981 c
982 d
983 +e
984 f
985 g
986 -h
987 <BLANKLINE>
988 (1, 1)
989
990The CONTEXT_DIFF flag causes failures that involve multi-line expected
991and actual outputs to be displayed using a context diff:
992
993 >>> # Reuse f() from the UNIFIED_DIFF example, above.
994 >>> test = doctest.DocTestFinder().find(f)[0]
995 >>> flags = doctest.CONTEXT_DIFF
996 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
997 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000998 Line 2, in f
999 Failed example:
1000 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001001 Differences (context diff):
1002 *** Expected
1003 --- Got
1004 ***************
1005 *** 1,8 ****
1006 a
1007 ! B
1008 c
1009 d
1010 f
1011 g
1012 - h
1013 <BLANKLINE>
1014 --- 1,8 ----
1015 a
1016 ! b
1017 c
1018 d
1019 + e
1020 f
1021 g
1022 <BLANKLINE>
1023 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001024
1025
1026The NDIFF_DIFF flag causes failures to use the difflib.Differ algorithm
1027used by the popular ndiff.py utility. This does intraline difference
1028marking, as well as interline differences.
1029
1030 >>> def f(x):
1031 ... r'''
1032 ... >>> print "a b c d e f g h i j k l m"
1033 ... a b c d e f g h i j k 1 m
1034 ... '''
1035 >>> test = doctest.DocTestFinder().find(f)[0]
1036 >>> flags = doctest.NDIFF_DIFF
1037 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1038 **********************************************************************
1039 Line 2, in f
1040 Failed example:
1041 print "a b c d e f g h i j k l m"
1042 Differences (ndiff with -expected +actual):
1043 - a b c d e f g h i j k 1 m
1044 ? ^
1045 + a b c d e f g h i j k l m
1046 ? + ++ ^
1047 <BLANKLINE>
1048 (1, 1)
1049 """
1050
Tim Peters8485b562004-08-04 18:46:34 +00001051 def option_directives(): r"""
1052Tests of `DocTestRunner`'s option directive mechanism.
1053
Edward Loper74bca7a2004-08-12 02:27:44 +00001054Option directives can be used to turn option flags on or off for a
1055single example. To turn an option on for an example, follow that
1056example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001057
1058 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001059 ... >>> print range(10) # should fail: no ellipsis
1060 ... [0, 1, ..., 9]
1061 ...
1062 ... >>> print range(10) # doctest: +ELLIPSIS
1063 ... [0, 1, ..., 9]
1064 ... '''
1065 >>> test = doctest.DocTestFinder().find(f)[0]
1066 >>> doctest.DocTestRunner(verbose=False).run(test)
1067 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001068 Line 2, in f
1069 Failed example:
1070 print range(10) # should fail: no ellipsis
1071 Expected:
1072 [0, 1, ..., 9]
1073 Got:
1074 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001075 (1, 2)
1076
1077To turn an option off for an example, follow that example with a
1078comment of the form ``# doctest: -OPTION``:
1079
1080 >>> def f(x): r'''
1081 ... >>> print range(10)
1082 ... [0, 1, ..., 9]
1083 ...
1084 ... >>> # should fail: no ellipsis
1085 ... >>> print range(10) # doctest: -ELLIPSIS
1086 ... [0, 1, ..., 9]
1087 ... '''
1088 >>> test = doctest.DocTestFinder().find(f)[0]
1089 >>> doctest.DocTestRunner(verbose=False,
1090 ... optionflags=doctest.ELLIPSIS).run(test)
1091 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001092 Line 6, in f
1093 Failed example:
1094 print range(10) # doctest: -ELLIPSIS
1095 Expected:
1096 [0, 1, ..., 9]
1097 Got:
1098 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001099 (1, 2)
1100
1101Option directives affect only the example that they appear with; they
1102do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001103
Edward Loper74bca7a2004-08-12 02:27:44 +00001104 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001105 ... >>> print range(10) # Should fail: no ellipsis
1106 ... [0, 1, ..., 9]
1107 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001108 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001109 ... [0, 1, ..., 9]
1110 ...
Tim Peters8485b562004-08-04 18:46:34 +00001111 ... >>> print range(10) # Should fail: no ellipsis
1112 ... [0, 1, ..., 9]
1113 ... '''
1114 >>> test = doctest.DocTestFinder().find(f)[0]
1115 >>> doctest.DocTestRunner(verbose=False).run(test)
1116 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001117 Line 2, in f
1118 Failed example:
1119 print range(10) # Should fail: no ellipsis
1120 Expected:
1121 [0, 1, ..., 9]
1122 Got:
1123 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001124 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001125 Line 8, in f
1126 Failed example:
1127 print range(10) # Should fail: no ellipsis
1128 Expected:
1129 [0, 1, ..., 9]
1130 Got:
1131 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001132 (2, 3)
1133
Edward Loper74bca7a2004-08-12 02:27:44 +00001134Multiple options may be modified by a single option directive. They
1135may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001136
1137 >>> def f(x): r'''
1138 ... >>> print range(10) # Should fail
1139 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001140 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001141 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001142 ... [0, 1, ..., 9]
1143 ... '''
1144 >>> test = doctest.DocTestFinder().find(f)[0]
1145 >>> doctest.DocTestRunner(verbose=False).run(test)
1146 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001147 Line 2, in f
1148 Failed example:
1149 print range(10) # Should fail
1150 Expected:
1151 [0, 1, ..., 9]
1152 Got:
1153 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001154 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001155
1156 >>> def f(x): r'''
1157 ... >>> print range(10) # Should fail
1158 ... [0, 1, ..., 9]
1159 ... >>> print range(10) # Should succeed
1160 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1161 ... [0, 1, ..., 9]
1162 ... '''
1163 >>> test = doctest.DocTestFinder().find(f)[0]
1164 >>> doctest.DocTestRunner(verbose=False).run(test)
1165 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001166 Line 2, in f
1167 Failed example:
1168 print range(10) # Should fail
1169 Expected:
1170 [0, 1, ..., 9]
1171 Got:
1172 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001173 (1, 2)
1174
1175 >>> def f(x): r'''
1176 ... >>> print range(10) # Should fail
1177 ... [0, 1, ..., 9]
1178 ... >>> print range(10) # Should succeed
1179 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1180 ... [0, 1, ..., 9]
1181 ... '''
1182 >>> test = doctest.DocTestFinder().find(f)[0]
1183 >>> doctest.DocTestRunner(verbose=False).run(test)
1184 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001185 Line 2, in f
1186 Failed example:
1187 print range(10) # Should fail
1188 Expected:
1189 [0, 1, ..., 9]
1190 Got:
1191 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001192 (1, 2)
1193
1194The option directive may be put on the line following the source, as
1195long as a continuation prompt is used:
1196
1197 >>> def f(x): r'''
1198 ... >>> print range(10)
1199 ... ... # doctest: +ELLIPSIS
1200 ... [0, 1, ..., 9]
1201 ... '''
1202 >>> test = doctest.DocTestFinder().find(f)[0]
1203 >>> doctest.DocTestRunner(verbose=False).run(test)
1204 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001205
Edward Loper74bca7a2004-08-12 02:27:44 +00001206For examples with multi-line source, the option directive may appear
1207at the end of any line:
1208
1209 >>> def f(x): r'''
1210 ... >>> for x in range(10): # doctest: +ELLIPSIS
1211 ... ... print x,
1212 ... 0 1 2 ... 9
1213 ...
1214 ... >>> for x in range(10):
1215 ... ... print x, # doctest: +ELLIPSIS
1216 ... 0 1 2 ... 9
1217 ... '''
1218 >>> test = doctest.DocTestFinder().find(f)[0]
1219 >>> doctest.DocTestRunner(verbose=False).run(test)
1220 (0, 2)
1221
1222If more than one line of an example with multi-line source has an
1223option directive, then they are combined:
1224
1225 >>> def f(x): r'''
1226 ... Should fail (option directive not on the last line):
1227 ... >>> for x in range(10): # doctest: +ELLIPSIS
1228 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1229 ... 0 1 2...9
1230 ... '''
1231 >>> test = doctest.DocTestFinder().find(f)[0]
1232 >>> doctest.DocTestRunner(verbose=False).run(test)
1233 (0, 1)
1234
1235It is an error to have a comment of the form ``# doctest:`` that is
1236*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1237``OPTION`` is an option that has been registered with
1238`register_option`:
1239
1240 >>> # Error: Option not registered
1241 >>> s = '>>> print 12 #doctest: +BADOPTION'
1242 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1243 Traceback (most recent call last):
1244 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1245
1246 >>> # Error: No + or - prefix
1247 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1248 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1249 Traceback (most recent call last):
1250 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1251
1252It is an error to use an option directive on a line that contains no
1253source:
1254
1255 >>> s = '>>> # doctest: +ELLIPSIS'
1256 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1257 Traceback (most recent call last):
1258 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 +00001259"""
1260
1261def test_testsource(): r"""
1262Unit tests for `testsource()`.
1263
1264The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001265test with that name in that module, and converts it to a script. The
1266example code is converted to regular Python code. The surrounding
1267words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001268
1269 >>> import test.test_doctest
1270 >>> name = 'test.test_doctest.sample_func'
1271 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001272 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001273 #
Tim Peters8485b562004-08-04 18:46:34 +00001274 print sample_func(22)
1275 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001276 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001277 #
Edward Lopera5db6002004-08-12 02:41:30 +00001278 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001279
1280 >>> name = 'test.test_doctest.SampleNewStyleClass'
1281 >>> print doctest.testsource(test.test_doctest, name)
1282 print '1\n2\n3'
1283 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001284 ## 1
1285 ## 2
1286 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001287
1288 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1289 >>> print doctest.testsource(test.test_doctest, name)
1290 print SampleClass.a_classmethod(10)
1291 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001292 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001293 print SampleClass(0).a_classmethod(10)
1294 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001295 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001296"""
1297
1298def test_debug(): r"""
1299
1300Create a docstring that we want to debug:
1301
1302 >>> s = '''
1303 ... >>> x = 12
1304 ... >>> print x
1305 ... 12
1306 ... '''
1307
1308Create some fake stdin input, to feed to the debugger:
1309
1310 >>> import tempfile
1311 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1312 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1313 >>> fake_stdin.seek(0)
1314 >>> real_stdin = sys.stdin
1315 >>> sys.stdin = fake_stdin
1316
1317Run the debugger on the docstring, and then restore sys.stdin.
1318
Tim Peters8485b562004-08-04 18:46:34 +00001319 >>> try:
1320 ... doctest.debug_src(s)
1321 ... finally:
1322 ... sys.stdin = real_stdin
1323 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001324 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001325 > <string>(1)?()
1326 (Pdb) 12
1327 --Return--
1328 > <string>(1)?()->None
1329 (Pdb) 12
1330 (Pdb)
1331
1332"""
1333
Jim Fulton356fd192004-08-09 11:34:47 +00001334def test_pdb_set_trace():
1335 r"""Using pdb.set_trace from a doctest
1336
Tim Peters413ced62004-08-09 15:43:47 +00001337 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001338 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001339 you use it. The doctest module changes sys.stdout so that it can
1340 capture program output. It also temporarily replaces pdb.set_trace
1341 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001342 see debugger output.
1343
1344 >>> doc = '''
1345 ... >>> x = 42
1346 ... >>> import pdb; pdb.set_trace()
1347 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001348 >>> parser = doctest.DocTestParser()
1349 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001350 >>> runner = doctest.DocTestRunner(verbose=False)
1351
1352 To demonstrate this, we'll create a fake standard input that
1353 captures our debugger input:
1354
1355 >>> import tempfile
1356 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1357 >>> fake_stdin.write('\n'.join([
1358 ... 'up', # up out of pdb.set_trace
1359 ... 'up', # up again to get out of our wrapper
1360 ... 'print x', # print data defined by the example
1361 ... 'continue', # stop debugging
1362 ... '']))
1363 >>> fake_stdin.seek(0)
1364 >>> real_stdin = sys.stdin
1365 >>> sys.stdin = fake_stdin
1366
Edward Loper74bca7a2004-08-12 02:27:44 +00001367 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001368 --Return--
1369 > ...set_trace()->None
1370 -> Pdb().set_trace()
1371 (Pdb) > ...set_trace()
1372 -> real_pdb_set_trace()
1373 (Pdb) > <string>(1)?()
1374 (Pdb) 42
1375 (Pdb) (0, 2)
1376
1377 >>> sys.stdin = real_stdin
1378 >>> fake_stdin.close()
1379
1380 You can also put pdb.set_trace in a function called from a test:
1381
1382 >>> def calls_set_trace():
1383 ... y=2
1384 ... import pdb; pdb.set_trace()
1385
1386 >>> doc = '''
1387 ... >>> x=1
1388 ... >>> calls_set_trace()
1389 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001390 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001391 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1392 >>> fake_stdin.write('\n'.join([
1393 ... 'up', # up out of pdb.set_trace
1394 ... 'up', # up again to get out of our wrapper
1395 ... 'print y', # print data defined in the function
1396 ... 'up', # out of function
1397 ... 'print x', # print data defined by the example
1398 ... 'continue', # stop debugging
1399 ... '']))
1400 >>> fake_stdin.seek(0)
1401 >>> real_stdin = sys.stdin
1402 >>> sys.stdin = fake_stdin
1403
Edward Loper74bca7a2004-08-12 02:27:44 +00001404 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001405 --Return--
1406 > ...set_trace()->None
1407 -> Pdb().set_trace()
1408 (Pdb) ...set_trace()
1409 -> real_pdb_set_trace()
1410 (Pdb) > <string>(3)calls_set_trace()
1411 (Pdb) 2
1412 (Pdb) > <string>(1)?()
1413 (Pdb) 1
1414 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001415 """
1416
Tim Peters19397e52004-08-06 22:02:59 +00001417def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001418 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001419
1420 We create a Suite by providing a module. A module can be provided
1421 by passing a module object:
1422
1423 >>> import unittest
1424 >>> import test.sample_doctest
1425 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1426 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001427 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001428
1429 We can also supply the module by name:
1430
1431 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1432 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001433 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001434
1435 We can use the current module:
1436
1437 >>> suite = test.sample_doctest.test_suite()
1438 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001439 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001440
1441 We can supply global variables. If we pass globs, they will be
1442 used instead of the module globals. Here we'll pass an empty
1443 globals, triggering an extra error:
1444
1445 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1446 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001447 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001448
1449 Alternatively, we can provide extra globals. Here we'll make an
1450 error go away by providing an extra global variable:
1451
1452 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1453 ... extraglobs={'y': 1})
1454 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001455 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001456
1457 You can pass option flags. Here we'll cause an extra error
1458 by disabling the blank-line feature:
1459
1460 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001461 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001462 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001463 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001464
Tim Peters1e277ee2004-08-07 05:37:52 +00001465 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001466
1467 >>> def setUp():
1468 ... import test.test_doctest
1469 ... test.test_doctest.sillySetup = True
1470
1471 >>> def tearDown():
1472 ... import test.test_doctest
1473 ... del test.test_doctest.sillySetup
1474
1475 Here, we installed a silly variable that the test expects:
1476
1477 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1478 ... setUp=setUp, tearDown=tearDown)
1479 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001480 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001481
1482 But the tearDown restores sanity:
1483
1484 >>> import test.test_doctest
1485 >>> test.test_doctest.sillySetup
1486 Traceback (most recent call last):
1487 ...
1488 AttributeError: 'module' object has no attribute 'sillySetup'
1489
1490 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001491 use a custom test_finder to to run just the test named bar.
1492 However, the test in the module docstring, and the two tests
1493 in the module __test__ dict, aren't filtered, so we actually
1494 run three tests besides bar's. The filtering mechanisms are
1495 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001496
1497 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001498 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001499 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1500 ... test_finder=finder)
1501 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001502 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001503 """
1504
1505def test_DocFileSuite():
1506 """We can test tests found in text files using a DocFileSuite.
1507
1508 We create a suite by providing the names of one or more text
1509 files that include examples:
1510
1511 >>> import unittest
1512 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1513 ... 'test_doctest2.txt')
1514 >>> suite.run(unittest.TestResult())
1515 <unittest.TestResult run=2 errors=0 failures=2>
1516
1517 The test files are looked for in the directory containing the
1518 calling module. A package keyword argument can be provided to
1519 specify a different relative location.
1520
1521 >>> import unittest
1522 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1523 ... 'test_doctest2.txt',
1524 ... package='test')
1525 >>> suite.run(unittest.TestResult())
1526 <unittest.TestResult run=2 errors=0 failures=2>
1527
1528 Note that '/' should be used as a path separator. It will be
1529 converted to a native separator at run time:
1530
1531
1532 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1533 >>> suite.run(unittest.TestResult())
1534 <unittest.TestResult run=1 errors=0 failures=1>
1535
1536 You can specify initial global variables:
1537
1538 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1539 ... 'test_doctest2.txt',
1540 ... globs={'favorite_color': 'blue'})
1541 >>> suite.run(unittest.TestResult())
1542 <unittest.TestResult run=2 errors=0 failures=1>
1543
1544 In this case, we supplied a missing favorite color. You can
1545 provide doctest options:
1546
1547 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1548 ... 'test_doctest2.txt',
1549 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1550 ... globs={'favorite_color': 'blue'})
1551 >>> suite.run(unittest.TestResult())
1552 <unittest.TestResult run=2 errors=0 failures=2>
1553
1554 And, you can provide setUp and tearDown functions:
1555
1556 You can supply setUp and teatDoen functions:
1557
1558 >>> def setUp():
1559 ... import test.test_doctest
1560 ... test.test_doctest.sillySetup = True
1561
1562 >>> def tearDown():
1563 ... import test.test_doctest
1564 ... del test.test_doctest.sillySetup
1565
1566 Here, we installed a silly variable that the test expects:
1567
1568 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1569 ... 'test_doctest2.txt',
1570 ... setUp=setUp, tearDown=tearDown)
1571 >>> suite.run(unittest.TestResult())
1572 <unittest.TestResult run=2 errors=0 failures=1>
1573
1574 But the tearDown restores sanity:
1575
1576 >>> import test.test_doctest
1577 >>> test.test_doctest.sillySetup
1578 Traceback (most recent call last):
1579 ...
1580 AttributeError: 'module' object has no attribute 'sillySetup'
1581
1582 """
1583
Jim Fulton07a349c2004-08-22 14:10:00 +00001584def test_trailing_space_in_test():
1585 """
Tim Petersa7def722004-08-23 22:13:22 +00001586 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001587
Jim Fulton07a349c2004-08-22 14:10:00 +00001588 >>> x, y = 'foo', ''
1589 >>> print x, y
1590 foo \n
1591 """
Tim Peters19397e52004-08-06 22:02:59 +00001592
Tim Petersa7def722004-08-23 22:13:22 +00001593# old_test1, ... used to live in doctest.py, but cluttered it. Note
1594# that these use the deprecated doctest.Tester, so should go away (or
1595# be rewritten) someday.
1596
1597# Ignore all warnings about the use of class Tester in this module.
1598# Note that the name of this module may differ depending on how it's
1599# imported, so the use of __name__ is important.
1600warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1601 __name__, 0)
1602
1603def old_test1(): r"""
1604>>> from doctest import Tester
1605>>> t = Tester(globs={'x': 42}, verbose=0)
1606>>> t.runstring(r'''
1607... >>> x = x * 2
1608... >>> print x
1609... 42
1610... ''', 'XYZ')
1611**********************************************************************
1612Line 3, in XYZ
1613Failed example:
1614 print x
1615Expected:
1616 42
1617Got:
1618 84
1619(1, 2)
1620>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1621(0, 2)
1622>>> t.summarize()
1623**********************************************************************
16241 items had failures:
1625 1 of 2 in XYZ
1626***Test Failed*** 1 failures.
1627(1, 4)
1628>>> t.summarize(verbose=1)
16291 items passed all tests:
1630 2 tests in example2
1631**********************************************************************
16321 items had failures:
1633 1 of 2 in XYZ
16344 tests in 2 items.
16353 passed and 1 failed.
1636***Test Failed*** 1 failures.
1637(1, 4)
1638"""
1639
1640def old_test2(): r"""
1641 >>> from doctest import Tester
1642 >>> t = Tester(globs={}, verbose=1)
1643 >>> test = r'''
1644 ... # just an example
1645 ... >>> x = 1 + 2
1646 ... >>> x
1647 ... 3
1648 ... '''
1649 >>> t.runstring(test, "Example")
1650 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00001651 Trying:
1652 x = 1 + 2
1653 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00001654 ok
Edward Loperaacf0832004-08-26 01:19:50 +00001655 Trying:
1656 x
1657 Expecting:
1658 3
Tim Petersa7def722004-08-23 22:13:22 +00001659 ok
1660 0 of 2 examples failed in string Example
1661 (0, 2)
1662"""
1663
1664def old_test3(): r"""
1665 >>> from doctest import Tester
1666 >>> t = Tester(globs={}, verbose=0)
1667 >>> def _f():
1668 ... '''Trivial docstring example.
1669 ... >>> assert 2 == 2
1670 ... '''
1671 ... return 32
1672 ...
1673 >>> t.rundoc(_f) # expect 0 failures in 1 example
1674 (0, 1)
1675"""
1676
1677def old_test4(): """
1678 >>> import new
1679 >>> m1 = new.module('_m1')
1680 >>> m2 = new.module('_m2')
1681 >>> test_data = \"""
1682 ... def _f():
1683 ... '''>>> assert 1 == 1
1684 ... '''
1685 ... def g():
1686 ... '''>>> assert 2 != 1
1687 ... '''
1688 ... class H:
1689 ... '''>>> assert 2 > 1
1690 ... '''
1691 ... def bar(self):
1692 ... '''>>> assert 1 < 2
1693 ... '''
1694 ... \"""
1695 >>> exec test_data in m1.__dict__
1696 >>> exec test_data in m2.__dict__
1697 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
1698
1699 Tests that objects outside m1 are excluded:
1700
1701 >>> from doctest import Tester
1702 >>> t = Tester(globs={}, verbose=0)
1703 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
1704 (0, 4)
1705
1706 Once more, not excluding stuff outside m1:
1707
1708 >>> t = Tester(globs={}, verbose=0)
1709 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
1710 (0, 8)
1711
1712 The exclusion of objects from outside the designated module is
1713 meant to be invoked automagically by testmod.
1714
1715 >>> doctest.testmod(m1, verbose=False)
1716 (0, 4)
1717"""
1718
Tim Peters8485b562004-08-04 18:46:34 +00001719######################################################################
1720## Main
1721######################################################################
1722
1723def test_main():
1724 # Check the doctest cases in doctest itself:
1725 test_support.run_doctest(doctest, verbosity=True)
1726 # Check the doctest cases defined here:
1727 from test import test_doctest
1728 test_support.run_doctest(test_doctest, verbosity=True)
1729
1730import trace, sys, re, StringIO
1731def test_coverage(coverdir):
1732 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1733 trace=0, count=1)
1734 tracer.run('reload(doctest); test_main()')
1735 r = tracer.results()
1736 print 'Writing coverage results...'
1737 r.write_results(show_missing=True, summary=True,
1738 coverdir=coverdir)
1739
1740if __name__ == '__main__':
1741 if '-c' in sys.argv:
1742 test_coverage('/tmp/doctest.cover')
1743 else:
1744 test_main()