blob: 2464b238d3a6ff76a86696f26fff425e18a08a0e [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
Edward Loper71f55af2004-08-26 01:41:51 +0000926The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +0000927and 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]
Edward Loper71f55af2004-08-26 01:41:51 +0000968 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +0000969 >>> 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')
Edward Loper56629292004-08-26 01:31:56 +0000974 Differences (unified diff with -expected +actual):
Tim Peters8485b562004-08-04 18:46:34 +0000975 @@ -1,8 +1,8 @@
976 a
977 -B
978 +b
979 c
980 d
981 +e
982 f
983 g
984 -h
985 <BLANKLINE>
986 (1, 1)
987
Edward Loper71f55af2004-08-26 01:41:51 +0000988The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +0000989and actual outputs to be displayed using a context diff:
990
Edward Loper71f55af2004-08-26 01:41:51 +0000991 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +0000992 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +0000993 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +0000994 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
995 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000996 Line 2, in f
997 Failed example:
998 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +0000999 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001000 ***************
1001 *** 1,8 ****
1002 a
1003 ! B
1004 c
1005 d
1006 f
1007 g
1008 - h
1009 <BLANKLINE>
1010 --- 1,8 ----
1011 a
1012 ! b
1013 c
1014 d
1015 + e
1016 f
1017 g
1018 <BLANKLINE>
1019 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001020
1021
Edward Loper71f55af2004-08-26 01:41:51 +00001022The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001023used by the popular ndiff.py utility. This does intraline difference
1024marking, as well as interline differences.
1025
1026 >>> def f(x):
1027 ... r'''
1028 ... >>> print "a b c d e f g h i j k l m"
1029 ... a b c d e f g h i j k 1 m
1030 ... '''
1031 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001032 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001033 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1034 **********************************************************************
1035 Line 2, in f
1036 Failed example:
1037 print "a b c d e f g h i j k l m"
1038 Differences (ndiff with -expected +actual):
1039 - a b c d e f g h i j k 1 m
1040 ? ^
1041 + a b c d e f g h i j k l m
1042 ? + ++ ^
1043 <BLANKLINE>
1044 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001045
1046The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1047failing example:
1048
1049 >>> def f(x):
1050 ... r'''
1051 ... >>> print 1 # first success
1052 ... 1
1053 ... >>> print 2 # first failure
1054 ... 200
1055 ... >>> print 3 # second failure
1056 ... 300
1057 ... >>> print 4 # second success
1058 ... 4
1059 ... >>> print 5 # third failure
1060 ... 500
1061 ... '''
1062 >>> test = doctest.DocTestFinder().find(f)[0]
1063 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1064 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1065 **********************************************************************
1066 Line 4, in f
1067 Failed example:
1068 print 2 # first failure
1069 Expected:
1070 200
1071 Got:
1072 2
1073 (3, 5)
1074
1075However, output from `report_start` is not supressed:
1076
1077 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
1078 Trying:
1079 print 1 # first success
1080 Expecting:
1081 1
1082 ok
1083 Trying:
1084 print 2 # first failure
1085 Expecting:
1086 200
1087 **********************************************************************
1088 Line 4, in f
1089 Failed example:
1090 print 2 # first failure
1091 Expected:
1092 200
1093 Got:
1094 2
1095 (3, 5)
1096
1097For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1098count as failures:
1099
1100 >>> def f(x):
1101 ... r'''
1102 ... >>> print 1 # first success
1103 ... 1
1104 ... >>> raise ValueError(2) # first failure
1105 ... 200
1106 ... >>> print 3 # second failure
1107 ... 300
1108 ... >>> print 4 # second success
1109 ... 4
1110 ... >>> print 5 # third failure
1111 ... 500
1112 ... '''
1113 >>> test = doctest.DocTestFinder().find(f)[0]
1114 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1115 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1116 ... # doctest: +ELLIPSIS
1117 **********************************************************************
1118 Line 4, in f
1119 Failed example:
1120 raise ValueError(2) # first failure
1121 Exception raised:
1122 ...
1123 ValueError: 2
1124 (3, 5)
1125
Tim Petersc6cbab02004-08-22 19:43:28 +00001126 """
1127
Tim Peters8485b562004-08-04 18:46:34 +00001128 def option_directives(): r"""
1129Tests of `DocTestRunner`'s option directive mechanism.
1130
Edward Loper74bca7a2004-08-12 02:27:44 +00001131Option directives can be used to turn option flags on or off for a
1132single example. To turn an option on for an example, follow that
1133example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001134
1135 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001136 ... >>> print range(10) # should fail: no ellipsis
1137 ... [0, 1, ..., 9]
1138 ...
1139 ... >>> print range(10) # doctest: +ELLIPSIS
1140 ... [0, 1, ..., 9]
1141 ... '''
1142 >>> test = doctest.DocTestFinder().find(f)[0]
1143 >>> doctest.DocTestRunner(verbose=False).run(test)
1144 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001145 Line 2, in f
1146 Failed example:
1147 print range(10) # should fail: no ellipsis
1148 Expected:
1149 [0, 1, ..., 9]
1150 Got:
1151 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001152 (1, 2)
1153
1154To turn an option off for an example, follow that example with a
1155comment of the form ``# doctest: -OPTION``:
1156
1157 >>> def f(x): r'''
1158 ... >>> print range(10)
1159 ... [0, 1, ..., 9]
1160 ...
1161 ... >>> # should fail: no ellipsis
1162 ... >>> print range(10) # doctest: -ELLIPSIS
1163 ... [0, 1, ..., 9]
1164 ... '''
1165 >>> test = doctest.DocTestFinder().find(f)[0]
1166 >>> doctest.DocTestRunner(verbose=False,
1167 ... optionflags=doctest.ELLIPSIS).run(test)
1168 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001169 Line 6, in f
1170 Failed example:
1171 print range(10) # doctest: -ELLIPSIS
1172 Expected:
1173 [0, 1, ..., 9]
1174 Got:
1175 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001176 (1, 2)
1177
1178Option directives affect only the example that they appear with; they
1179do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001180
Edward Loper74bca7a2004-08-12 02:27:44 +00001181 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001182 ... >>> print range(10) # Should fail: no ellipsis
1183 ... [0, 1, ..., 9]
1184 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001185 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001186 ... [0, 1, ..., 9]
1187 ...
Tim Peters8485b562004-08-04 18:46:34 +00001188 ... >>> print range(10) # Should fail: no ellipsis
1189 ... [0, 1, ..., 9]
1190 ... '''
1191 >>> test = doctest.DocTestFinder().find(f)[0]
1192 >>> doctest.DocTestRunner(verbose=False).run(test)
1193 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001194 Line 2, in f
1195 Failed example:
1196 print range(10) # Should fail: no ellipsis
1197 Expected:
1198 [0, 1, ..., 9]
1199 Got:
1200 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001201 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001202 Line 8, in f
1203 Failed example:
1204 print range(10) # Should fail: no ellipsis
1205 Expected:
1206 [0, 1, ..., 9]
1207 Got:
1208 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001209 (2, 3)
1210
Edward Loper74bca7a2004-08-12 02:27:44 +00001211Multiple options may be modified by a single option directive. They
1212may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001213
1214 >>> def f(x): r'''
1215 ... >>> print range(10) # Should fail
1216 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001217 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001218 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001219 ... [0, 1, ..., 9]
1220 ... '''
1221 >>> test = doctest.DocTestFinder().find(f)[0]
1222 >>> doctest.DocTestRunner(verbose=False).run(test)
1223 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001224 Line 2, in f
1225 Failed example:
1226 print range(10) # Should fail
1227 Expected:
1228 [0, 1, ..., 9]
1229 Got:
1230 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001231 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001232
1233 >>> def f(x): r'''
1234 ... >>> print range(10) # Should fail
1235 ... [0, 1, ..., 9]
1236 ... >>> print range(10) # Should succeed
1237 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1238 ... [0, 1, ..., 9]
1239 ... '''
1240 >>> test = doctest.DocTestFinder().find(f)[0]
1241 >>> doctest.DocTestRunner(verbose=False).run(test)
1242 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001243 Line 2, in f
1244 Failed example:
1245 print range(10) # Should fail
1246 Expected:
1247 [0, 1, ..., 9]
1248 Got:
1249 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001250 (1, 2)
1251
1252 >>> def f(x): r'''
1253 ... >>> print range(10) # Should fail
1254 ... [0, 1, ..., 9]
1255 ... >>> print range(10) # Should succeed
1256 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1257 ... [0, 1, ..., 9]
1258 ... '''
1259 >>> test = doctest.DocTestFinder().find(f)[0]
1260 >>> doctest.DocTestRunner(verbose=False).run(test)
1261 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001262 Line 2, in f
1263 Failed example:
1264 print range(10) # Should fail
1265 Expected:
1266 [0, 1, ..., 9]
1267 Got:
1268 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001269 (1, 2)
1270
1271The option directive may be put on the line following the source, as
1272long as a continuation prompt is used:
1273
1274 >>> def f(x): r'''
1275 ... >>> print range(10)
1276 ... ... # doctest: +ELLIPSIS
1277 ... [0, 1, ..., 9]
1278 ... '''
1279 >>> test = doctest.DocTestFinder().find(f)[0]
1280 >>> doctest.DocTestRunner(verbose=False).run(test)
1281 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001282
Edward Loper74bca7a2004-08-12 02:27:44 +00001283For examples with multi-line source, the option directive may appear
1284at the end of any line:
1285
1286 >>> def f(x): r'''
1287 ... >>> for x in range(10): # doctest: +ELLIPSIS
1288 ... ... print x,
1289 ... 0 1 2 ... 9
1290 ...
1291 ... >>> for x in range(10):
1292 ... ... print x, # doctest: +ELLIPSIS
1293 ... 0 1 2 ... 9
1294 ... '''
1295 >>> test = doctest.DocTestFinder().find(f)[0]
1296 >>> doctest.DocTestRunner(verbose=False).run(test)
1297 (0, 2)
1298
1299If more than one line of an example with multi-line source has an
1300option directive, then they are combined:
1301
1302 >>> def f(x): r'''
1303 ... Should fail (option directive not on the last line):
1304 ... >>> for x in range(10): # doctest: +ELLIPSIS
1305 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1306 ... 0 1 2...9
1307 ... '''
1308 >>> test = doctest.DocTestFinder().find(f)[0]
1309 >>> doctest.DocTestRunner(verbose=False).run(test)
1310 (0, 1)
1311
1312It is an error to have a comment of the form ``# doctest:`` that is
1313*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1314``OPTION`` is an option that has been registered with
1315`register_option`:
1316
1317 >>> # Error: Option not registered
1318 >>> s = '>>> print 12 #doctest: +BADOPTION'
1319 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1320 Traceback (most recent call last):
1321 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1322
1323 >>> # Error: No + or - prefix
1324 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1325 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1326 Traceback (most recent call last):
1327 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1328
1329It is an error to use an option directive on a line that contains no
1330source:
1331
1332 >>> s = '>>> # doctest: +ELLIPSIS'
1333 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1334 Traceback (most recent call last):
1335 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 +00001336"""
1337
1338def test_testsource(): r"""
1339Unit tests for `testsource()`.
1340
1341The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001342test with that name in that module, and converts it to a script. The
1343example code is converted to regular Python code. The surrounding
1344words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001345
1346 >>> import test.test_doctest
1347 >>> name = 'test.test_doctest.sample_func'
1348 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001349 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001350 #
Tim Peters8485b562004-08-04 18:46:34 +00001351 print sample_func(22)
1352 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001353 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001354 #
Edward Lopera5db6002004-08-12 02:41:30 +00001355 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001356
1357 >>> name = 'test.test_doctest.SampleNewStyleClass'
1358 >>> print doctest.testsource(test.test_doctest, name)
1359 print '1\n2\n3'
1360 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001361 ## 1
1362 ## 2
1363 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001364
1365 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1366 >>> print doctest.testsource(test.test_doctest, name)
1367 print SampleClass.a_classmethod(10)
1368 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001369 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001370 print SampleClass(0).a_classmethod(10)
1371 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001372 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001373"""
1374
1375def test_debug(): r"""
1376
1377Create a docstring that we want to debug:
1378
1379 >>> s = '''
1380 ... >>> x = 12
1381 ... >>> print x
1382 ... 12
1383 ... '''
1384
1385Create some fake stdin input, to feed to the debugger:
1386
1387 >>> import tempfile
1388 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1389 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1390 >>> fake_stdin.seek(0)
1391 >>> real_stdin = sys.stdin
1392 >>> sys.stdin = fake_stdin
1393
1394Run the debugger on the docstring, and then restore sys.stdin.
1395
Tim Peters8485b562004-08-04 18:46:34 +00001396 >>> try:
1397 ... doctest.debug_src(s)
1398 ... finally:
1399 ... sys.stdin = real_stdin
1400 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001401 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001402 > <string>(1)?()
1403 (Pdb) 12
1404 --Return--
1405 > <string>(1)?()->None
1406 (Pdb) 12
1407 (Pdb)
1408
1409"""
1410
Jim Fulton356fd192004-08-09 11:34:47 +00001411def test_pdb_set_trace():
1412 r"""Using pdb.set_trace from a doctest
1413
Tim Peters413ced62004-08-09 15:43:47 +00001414 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001415 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001416 you use it. The doctest module changes sys.stdout so that it can
1417 capture program output. It also temporarily replaces pdb.set_trace
1418 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001419 see debugger output.
1420
1421 >>> doc = '''
1422 ... >>> x = 42
1423 ... >>> import pdb; pdb.set_trace()
1424 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001425 >>> parser = doctest.DocTestParser()
1426 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001427 >>> runner = doctest.DocTestRunner(verbose=False)
1428
1429 To demonstrate this, we'll create a fake standard input that
1430 captures our debugger input:
1431
1432 >>> import tempfile
1433 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1434 >>> fake_stdin.write('\n'.join([
1435 ... 'up', # up out of pdb.set_trace
1436 ... 'up', # up again to get out of our wrapper
1437 ... 'print x', # print data defined by the example
1438 ... 'continue', # stop debugging
1439 ... '']))
1440 >>> fake_stdin.seek(0)
1441 >>> real_stdin = sys.stdin
1442 >>> sys.stdin = fake_stdin
1443
Edward Loper74bca7a2004-08-12 02:27:44 +00001444 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001445 --Return--
1446 > ...set_trace()->None
1447 -> Pdb().set_trace()
1448 (Pdb) > ...set_trace()
1449 -> real_pdb_set_trace()
1450 (Pdb) > <string>(1)?()
1451 (Pdb) 42
1452 (Pdb) (0, 2)
1453
1454 >>> sys.stdin = real_stdin
1455 >>> fake_stdin.close()
1456
1457 You can also put pdb.set_trace in a function called from a test:
1458
1459 >>> def calls_set_trace():
1460 ... y=2
1461 ... import pdb; pdb.set_trace()
1462
1463 >>> doc = '''
1464 ... >>> x=1
1465 ... >>> calls_set_trace()
1466 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001467 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001468 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1469 >>> fake_stdin.write('\n'.join([
1470 ... 'up', # up out of pdb.set_trace
1471 ... 'up', # up again to get out of our wrapper
1472 ... 'print y', # print data defined in the function
1473 ... 'up', # out of function
1474 ... 'print x', # print data defined by the example
1475 ... 'continue', # stop debugging
1476 ... '']))
1477 >>> fake_stdin.seek(0)
1478 >>> real_stdin = sys.stdin
1479 >>> sys.stdin = fake_stdin
1480
Edward Loper74bca7a2004-08-12 02:27:44 +00001481 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001482 --Return--
1483 > ...set_trace()->None
1484 -> Pdb().set_trace()
1485 (Pdb) ...set_trace()
1486 -> real_pdb_set_trace()
1487 (Pdb) > <string>(3)calls_set_trace()
1488 (Pdb) 2
1489 (Pdb) > <string>(1)?()
1490 (Pdb) 1
1491 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001492 """
1493
Tim Peters19397e52004-08-06 22:02:59 +00001494def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001495 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001496
1497 We create a Suite by providing a module. A module can be provided
1498 by passing a module object:
1499
1500 >>> import unittest
1501 >>> import test.sample_doctest
1502 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1503 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001504 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001505
1506 We can also supply the module by name:
1507
1508 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1509 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001510 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001511
1512 We can use the current module:
1513
1514 >>> suite = test.sample_doctest.test_suite()
1515 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001516 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001517
1518 We can supply global variables. If we pass globs, they will be
1519 used instead of the module globals. Here we'll pass an empty
1520 globals, triggering an extra error:
1521
1522 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1523 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001524 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001525
1526 Alternatively, we can provide extra globals. Here we'll make an
1527 error go away by providing an extra global variable:
1528
1529 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1530 ... extraglobs={'y': 1})
1531 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001532 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001533
1534 You can pass option flags. Here we'll cause an extra error
1535 by disabling the blank-line feature:
1536
1537 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001538 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001539 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001540 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001541
Tim Peters1e277ee2004-08-07 05:37:52 +00001542 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001543
1544 >>> def setUp():
1545 ... import test.test_doctest
1546 ... test.test_doctest.sillySetup = True
1547
1548 >>> def tearDown():
1549 ... import test.test_doctest
1550 ... del test.test_doctest.sillySetup
1551
1552 Here, we installed a silly variable that the test expects:
1553
1554 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1555 ... setUp=setUp, tearDown=tearDown)
1556 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001557 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001558
1559 But the tearDown restores sanity:
1560
1561 >>> import test.test_doctest
1562 >>> test.test_doctest.sillySetup
1563 Traceback (most recent call last):
1564 ...
1565 AttributeError: 'module' object has no attribute 'sillySetup'
1566
1567 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001568 use a custom test_finder to to run just the test named bar.
1569 However, the test in the module docstring, and the two tests
1570 in the module __test__ dict, aren't filtered, so we actually
1571 run three tests besides bar's. The filtering mechanisms are
1572 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001573
1574 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001575 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001576 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1577 ... test_finder=finder)
1578 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001579 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001580 """
1581
1582def test_DocFileSuite():
1583 """We can test tests found in text files using a DocFileSuite.
1584
1585 We create a suite by providing the names of one or more text
1586 files that include examples:
1587
1588 >>> import unittest
1589 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1590 ... 'test_doctest2.txt')
1591 >>> suite.run(unittest.TestResult())
1592 <unittest.TestResult run=2 errors=0 failures=2>
1593
1594 The test files are looked for in the directory containing the
1595 calling module. A package keyword argument can be provided to
1596 specify a different relative location.
1597
1598 >>> import unittest
1599 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1600 ... 'test_doctest2.txt',
1601 ... package='test')
1602 >>> suite.run(unittest.TestResult())
1603 <unittest.TestResult run=2 errors=0 failures=2>
1604
1605 Note that '/' should be used as a path separator. It will be
1606 converted to a native separator at run time:
1607
1608
1609 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1610 >>> suite.run(unittest.TestResult())
1611 <unittest.TestResult run=1 errors=0 failures=1>
1612
1613 You can specify initial global variables:
1614
1615 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1616 ... 'test_doctest2.txt',
1617 ... globs={'favorite_color': 'blue'})
1618 >>> suite.run(unittest.TestResult())
1619 <unittest.TestResult run=2 errors=0 failures=1>
1620
1621 In this case, we supplied a missing favorite color. You can
1622 provide doctest options:
1623
1624 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1625 ... 'test_doctest2.txt',
1626 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1627 ... globs={'favorite_color': 'blue'})
1628 >>> suite.run(unittest.TestResult())
1629 <unittest.TestResult run=2 errors=0 failures=2>
1630
1631 And, you can provide setUp and tearDown functions:
1632
1633 You can supply setUp and teatDoen functions:
1634
1635 >>> def setUp():
1636 ... import test.test_doctest
1637 ... test.test_doctest.sillySetup = True
1638
1639 >>> def tearDown():
1640 ... import test.test_doctest
1641 ... del test.test_doctest.sillySetup
1642
1643 Here, we installed a silly variable that the test expects:
1644
1645 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1646 ... 'test_doctest2.txt',
1647 ... setUp=setUp, tearDown=tearDown)
1648 >>> suite.run(unittest.TestResult())
1649 <unittest.TestResult run=2 errors=0 failures=1>
1650
1651 But the tearDown restores sanity:
1652
1653 >>> import test.test_doctest
1654 >>> test.test_doctest.sillySetup
1655 Traceback (most recent call last):
1656 ...
1657 AttributeError: 'module' object has no attribute 'sillySetup'
1658
1659 """
1660
Jim Fulton07a349c2004-08-22 14:10:00 +00001661def test_trailing_space_in_test():
1662 """
Tim Petersa7def722004-08-23 22:13:22 +00001663 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001664
Jim Fulton07a349c2004-08-22 14:10:00 +00001665 >>> x, y = 'foo', ''
1666 >>> print x, y
1667 foo \n
1668 """
Tim Peters19397e52004-08-06 22:02:59 +00001669
Tim Petersa7def722004-08-23 22:13:22 +00001670# old_test1, ... used to live in doctest.py, but cluttered it. Note
1671# that these use the deprecated doctest.Tester, so should go away (or
1672# be rewritten) someday.
1673
1674# Ignore all warnings about the use of class Tester in this module.
1675# Note that the name of this module may differ depending on how it's
1676# imported, so the use of __name__ is important.
1677warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1678 __name__, 0)
1679
1680def old_test1(): r"""
1681>>> from doctest import Tester
1682>>> t = Tester(globs={'x': 42}, verbose=0)
1683>>> t.runstring(r'''
1684... >>> x = x * 2
1685... >>> print x
1686... 42
1687... ''', 'XYZ')
1688**********************************************************************
1689Line 3, in XYZ
1690Failed example:
1691 print x
1692Expected:
1693 42
1694Got:
1695 84
1696(1, 2)
1697>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1698(0, 2)
1699>>> t.summarize()
1700**********************************************************************
17011 items had failures:
1702 1 of 2 in XYZ
1703***Test Failed*** 1 failures.
1704(1, 4)
1705>>> t.summarize(verbose=1)
17061 items passed all tests:
1707 2 tests in example2
1708**********************************************************************
17091 items had failures:
1710 1 of 2 in XYZ
17114 tests in 2 items.
17123 passed and 1 failed.
1713***Test Failed*** 1 failures.
1714(1, 4)
1715"""
1716
1717def old_test2(): r"""
1718 >>> from doctest import Tester
1719 >>> t = Tester(globs={}, verbose=1)
1720 >>> test = r'''
1721 ... # just an example
1722 ... >>> x = 1 + 2
1723 ... >>> x
1724 ... 3
1725 ... '''
1726 >>> t.runstring(test, "Example")
1727 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00001728 Trying:
1729 x = 1 + 2
1730 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00001731 ok
Edward Loperaacf0832004-08-26 01:19:50 +00001732 Trying:
1733 x
1734 Expecting:
1735 3
Tim Petersa7def722004-08-23 22:13:22 +00001736 ok
1737 0 of 2 examples failed in string Example
1738 (0, 2)
1739"""
1740
1741def old_test3(): r"""
1742 >>> from doctest import Tester
1743 >>> t = Tester(globs={}, verbose=0)
1744 >>> def _f():
1745 ... '''Trivial docstring example.
1746 ... >>> assert 2 == 2
1747 ... '''
1748 ... return 32
1749 ...
1750 >>> t.rundoc(_f) # expect 0 failures in 1 example
1751 (0, 1)
1752"""
1753
1754def old_test4(): """
1755 >>> import new
1756 >>> m1 = new.module('_m1')
1757 >>> m2 = new.module('_m2')
1758 >>> test_data = \"""
1759 ... def _f():
1760 ... '''>>> assert 1 == 1
1761 ... '''
1762 ... def g():
1763 ... '''>>> assert 2 != 1
1764 ... '''
1765 ... class H:
1766 ... '''>>> assert 2 > 1
1767 ... '''
1768 ... def bar(self):
1769 ... '''>>> assert 1 < 2
1770 ... '''
1771 ... \"""
1772 >>> exec test_data in m1.__dict__
1773 >>> exec test_data in m2.__dict__
1774 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
1775
1776 Tests that objects outside m1 are excluded:
1777
1778 >>> from doctest import Tester
1779 >>> t = Tester(globs={}, verbose=0)
1780 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
1781 (0, 4)
1782
1783 Once more, not excluding stuff outside m1:
1784
1785 >>> t = Tester(globs={}, verbose=0)
1786 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
1787 (0, 8)
1788
1789 The exclusion of objects from outside the designated module is
1790 meant to be invoked automagically by testmod.
1791
1792 >>> doctest.testmod(m1, verbose=False)
1793 (0, 4)
1794"""
1795
Tim Peters8485b562004-08-04 18:46:34 +00001796######################################################################
1797## Main
1798######################################################################
1799
1800def test_main():
1801 # Check the doctest cases in doctest itself:
1802 test_support.run_doctest(doctest, verbosity=True)
1803 # Check the doctest cases defined here:
1804 from test import test_doctest
1805 test_support.run_doctest(test_doctest, verbosity=True)
1806
1807import trace, sys, re, StringIO
1808def test_coverage(coverdir):
1809 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1810 trace=0, count=1)
1811 tracer.run('reload(doctest); test_main()')
1812 r = tracer.results()
1813 print 'Writing coverage results...'
1814 r.write_results(show_missing=True, summary=True,
1815 coverdir=coverdir)
1816
1817if __name__ == '__main__':
1818 if '-c' in sys.argv:
1819 test_coverage('/tmp/doctest.cover')
1820 else:
1821 test_main()