blob: a9076a6f88c6af504f05ca62d2a7b986ccb19bfd [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)
594 Trying: x = 12
595 Expecting: nothing
596 ok
597 Trying: print x
598 Expecting: 14
599 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000600 Line 3, in f
601 Failed example:
602 print x
603 Expected:
604 14
605 Got:
606 12
Tim Peters8485b562004-08-04 18:46:34 +0000607 Trying: x/2
608 Expecting: 6
609 ok
610 (1, 3)
611"""
612 def verbose_flag(): r"""
613The `verbose` flag makes the test runner generate more detailed
614output:
615
616 >>> def f(x):
617 ... '''
618 ... >>> x = 12
619 ... >>> print x
620 ... 12
621 ... >>> x/2
622 ... 6
623 ... '''
624 >>> test = doctest.DocTestFinder().find(f)[0]
625
626 >>> doctest.DocTestRunner(verbose=True).run(test)
627 Trying: x = 12
628 Expecting: nothing
629 ok
630 Trying: print x
631 Expecting: 12
632 ok
633 Trying: x/2
634 Expecting: 6
635 ok
636 (0, 3)
637
638If the `verbose` flag is unspecified, then the output will be verbose
639iff `-v` appears in sys.argv:
640
641 >>> # Save the real sys.argv list.
642 >>> old_argv = sys.argv
643
644 >>> # If -v does not appear in sys.argv, then output isn't verbose.
645 >>> sys.argv = ['test']
646 >>> doctest.DocTestRunner().run(test)
647 (0, 3)
648
649 >>> # If -v does appear in sys.argv, then output is verbose.
650 >>> sys.argv = ['test', '-v']
651 >>> doctest.DocTestRunner().run(test)
652 Trying: x = 12
653 Expecting: nothing
654 ok
655 Trying: print x
656 Expecting: 12
657 ok
658 Trying: x/2
659 Expecting: 6
660 ok
661 (0, 3)
662
663 >>> # Restore sys.argv
664 >>> sys.argv = old_argv
665
666In the remaining examples, the test runner's verbosity will be
667explicitly set, to ensure that the test behavior is consistent.
668 """
669 def exceptions(): r"""
670Tests of `DocTestRunner`'s exception handling.
671
672An expected exception is specified with a traceback message. The
673lines between the first line and the type/value may be omitted or
674replaced with any other string:
675
676 >>> def f(x):
677 ... '''
678 ... >>> x = 12
679 ... >>> print x/0
680 ... Traceback (most recent call last):
681 ... ZeroDivisionError: integer division or modulo by zero
682 ... '''
683 >>> test = doctest.DocTestFinder().find(f)[0]
684 >>> doctest.DocTestRunner(verbose=False).run(test)
685 (0, 2)
686
Edward Loper19b19582004-08-25 23:07:03 +0000687An example may not generate output before it raises an exception; if
688it does, then the traceback message will not be recognized as
689signaling an expected exception, so the example will be reported as an
690unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000691
692 >>> def f(x):
693 ... '''
694 ... >>> x = 12
695 ... >>> print 'pre-exception output', x/0
696 ... pre-exception output
697 ... Traceback (most recent call last):
698 ... ZeroDivisionError: integer division or modulo by zero
699 ... '''
700 >>> test = doctest.DocTestFinder().find(f)[0]
701 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000702 ... # doctest: +ELLIPSIS
703 **********************************************************************
704 Line 3, in f
705 Failed example:
706 print 'pre-exception output', x/0
707 Exception raised:
708 ...
709 ZeroDivisionError: integer division or modulo by zero
710 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000711
712Exception messages may contain newlines:
713
714 >>> def f(x):
715 ... r'''
716 ... >>> raise ValueError, 'multi\nline\nmessage'
717 ... Traceback (most recent call last):
718 ... ValueError: multi
719 ... line
720 ... message
721 ... '''
722 >>> test = doctest.DocTestFinder().find(f)[0]
723 >>> doctest.DocTestRunner(verbose=False).run(test)
724 (0, 1)
725
726If an exception is expected, but an exception with the wrong type or
727message is raised, then it is reported as a failure:
728
729 >>> def f(x):
730 ... r'''
731 ... >>> raise ValueError, 'message'
732 ... Traceback (most recent call last):
733 ... ValueError: wrong message
734 ... '''
735 >>> test = doctest.DocTestFinder().find(f)[0]
736 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000737 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000738 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000739 Line 2, in f
740 Failed example:
741 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000742 Expected:
743 Traceback (most recent call last):
744 ValueError: wrong message
745 Got:
746 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000747 ...
Tim Peters8485b562004-08-04 18:46:34 +0000748 ValueError: message
749 (1, 1)
750
751If an exception is raised but not expected, then it is reported as an
752unexpected exception:
753
Tim Peters8485b562004-08-04 18:46:34 +0000754 >>> def f(x):
755 ... r'''
756 ... >>> 1/0
757 ... 0
758 ... '''
759 >>> test = doctest.DocTestFinder().find(f)[0]
760 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000761 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000762 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000763 Line 2, in f
764 Failed example:
765 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000766 Exception raised:
767 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000768 ...
Tim Peters8485b562004-08-04 18:46:34 +0000769 ZeroDivisionError: integer division or modulo by zero
770 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000771"""
772 def optionflags(): r"""
773Tests of `DocTestRunner`'s option flag handling.
774
775Several option flags can be used to customize the behavior of the test
776runner. These are defined as module constants in doctest, and passed
777to the DocTestRunner constructor (multiple constants should be or-ed
778together).
779
780The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
781and 1/0:
782
783 >>> def f(x):
784 ... '>>> True\n1\n'
785
786 >>> # Without the flag:
787 >>> test = doctest.DocTestFinder().find(f)[0]
788 >>> doctest.DocTestRunner(verbose=False).run(test)
789 (0, 1)
790
791 >>> # With the flag:
792 >>> test = doctest.DocTestFinder().find(f)[0]
793 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
794 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
795 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000796 Line 1, in f
797 Failed example:
798 True
799 Expected:
800 1
801 Got:
802 True
Tim Peters8485b562004-08-04 18:46:34 +0000803 (1, 1)
804
805The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
806and the '<BLANKLINE>' marker:
807
808 >>> def f(x):
809 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
810
811 >>> # Without the flag:
812 >>> test = doctest.DocTestFinder().find(f)[0]
813 >>> doctest.DocTestRunner(verbose=False).run(test)
814 (0, 1)
815
816 >>> # With the flag:
817 >>> test = doctest.DocTestFinder().find(f)[0]
818 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
819 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
820 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000821 Line 1, in f
822 Failed example:
823 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000824 Expected:
825 a
826 <BLANKLINE>
827 b
828 Got:
829 a
830 <BLANKLINE>
831 b
832 (1, 1)
833
834The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
835treated as equal:
836
837 >>> def f(x):
838 ... '>>> print 1, 2, 3\n 1 2\n 3'
839
840 >>> # Without the flag:
841 >>> test = doctest.DocTestFinder().find(f)[0]
842 >>> doctest.DocTestRunner(verbose=False).run(test)
843 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000844 Line 1, in f
845 Failed example:
846 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000847 Expected:
848 1 2
849 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000850 Got:
851 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000852 (1, 1)
853
854 >>> # With the flag:
855 >>> test = doctest.DocTestFinder().find(f)[0]
856 >>> flags = doctest.NORMALIZE_WHITESPACE
857 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
858 (0, 1)
859
Tim Peters026f8dc2004-08-19 16:38:58 +0000860 An example from the docs:
861 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
862 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
863 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
864
Tim Peters8485b562004-08-04 18:46:34 +0000865The ELLIPSIS flag causes ellipsis marker ("...") in the expected
866output to match any substring in the actual output:
867
868 >>> def f(x):
869 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
870
871 >>> # Without the flag:
872 >>> test = doctest.DocTestFinder().find(f)[0]
873 >>> doctest.DocTestRunner(verbose=False).run(test)
874 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000875 Line 1, in f
876 Failed example:
877 print range(15)
878 Expected:
879 [0, 1, 2, ..., 14]
880 Got:
881 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +0000882 (1, 1)
883
884 >>> # With the flag:
885 >>> test = doctest.DocTestFinder().find(f)[0]
886 >>> flags = doctest.ELLIPSIS
887 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
888 (0, 1)
889
Tim Peterse594bee2004-08-22 01:47:51 +0000890 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +0000891
892 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +0000893 ... print i**2, #doctest: +ELLIPSIS
894 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +0000895
Tim Peters026f8dc2004-08-19 16:38:58 +0000896 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000897
898 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +0000899 ... print i,
900 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +0000901
Tim Peters026f8dc2004-08-19 16:38:58 +0000902 Examples from the docs:
903
904 >>> print range(20) # doctest:+ELLIPSIS
905 [0, 1, ..., 18, 19]
906
907 >>> print range(20) # doctest: +ELLIPSIS
908 ... # doctest: +NORMALIZE_WHITESPACE
909 [0, 1, ..., 18, 19]
910
Tim Peters8485b562004-08-04 18:46:34 +0000911The UNIFIED_DIFF flag causes failures that involve multi-line expected
912and actual outputs to be displayed using a unified diff:
913
914 >>> def f(x):
915 ... r'''
916 ... >>> print '\n'.join('abcdefg')
917 ... a
918 ... B
919 ... c
920 ... d
921 ... f
922 ... g
923 ... h
924 ... '''
925
926 >>> # Without the flag:
927 >>> test = doctest.DocTestFinder().find(f)[0]
928 >>> doctest.DocTestRunner(verbose=False).run(test)
929 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000930 Line 2, in f
931 Failed example:
932 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000933 Expected:
934 a
935 B
936 c
937 d
938 f
939 g
940 h
941 Got:
942 a
943 b
944 c
945 d
946 e
947 f
948 g
949 (1, 1)
950
951 >>> # With the flag:
952 >>> test = doctest.DocTestFinder().find(f)[0]
953 >>> flags = doctest.UNIFIED_DIFF
954 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
955 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000956 Line 2, in f
957 Failed example:
958 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000959 Differences (unified diff):
960 --- Expected
961 +++ Got
962 @@ -1,8 +1,8 @@
963 a
964 -B
965 +b
966 c
967 d
968 +e
969 f
970 g
971 -h
972 <BLANKLINE>
973 (1, 1)
974
975The CONTEXT_DIFF flag causes failures that involve multi-line expected
976and actual outputs to be displayed using a context diff:
977
978 >>> # Reuse f() from the UNIFIED_DIFF example, above.
979 >>> test = doctest.DocTestFinder().find(f)[0]
980 >>> flags = doctest.CONTEXT_DIFF
981 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
982 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000983 Line 2, in f
984 Failed example:
985 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000986 Differences (context diff):
987 *** Expected
988 --- Got
989 ***************
990 *** 1,8 ****
991 a
992 ! B
993 c
994 d
995 f
996 g
997 - h
998 <BLANKLINE>
999 --- 1,8 ----
1000 a
1001 ! b
1002 c
1003 d
1004 + e
1005 f
1006 g
1007 <BLANKLINE>
1008 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001009
1010
1011The NDIFF_DIFF flag causes failures to use the difflib.Differ algorithm
1012used by the popular ndiff.py utility. This does intraline difference
1013marking, as well as interline differences.
1014
1015 >>> def f(x):
1016 ... r'''
1017 ... >>> print "a b c d e f g h i j k l m"
1018 ... a b c d e f g h i j k 1 m
1019 ... '''
1020 >>> test = doctest.DocTestFinder().find(f)[0]
1021 >>> flags = doctest.NDIFF_DIFF
1022 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1023 **********************************************************************
1024 Line 2, in f
1025 Failed example:
1026 print "a b c d e f g h i j k l m"
1027 Differences (ndiff with -expected +actual):
1028 - a b c d e f g h i j k 1 m
1029 ? ^
1030 + a b c d e f g h i j k l m
1031 ? + ++ ^
1032 <BLANKLINE>
1033 (1, 1)
1034 """
1035
Tim Peters8485b562004-08-04 18:46:34 +00001036 def option_directives(): r"""
1037Tests of `DocTestRunner`'s option directive mechanism.
1038
Edward Loper74bca7a2004-08-12 02:27:44 +00001039Option directives can be used to turn option flags on or off for a
1040single example. To turn an option on for an example, follow that
1041example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001042
1043 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001044 ... >>> print range(10) # should fail: no ellipsis
1045 ... [0, 1, ..., 9]
1046 ...
1047 ... >>> print range(10) # doctest: +ELLIPSIS
1048 ... [0, 1, ..., 9]
1049 ... '''
1050 >>> test = doctest.DocTestFinder().find(f)[0]
1051 >>> doctest.DocTestRunner(verbose=False).run(test)
1052 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001053 Line 2, in f
1054 Failed example:
1055 print range(10) # should fail: no ellipsis
1056 Expected:
1057 [0, 1, ..., 9]
1058 Got:
1059 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001060 (1, 2)
1061
1062To turn an option off for an example, follow that example with a
1063comment of the form ``# doctest: -OPTION``:
1064
1065 >>> def f(x): r'''
1066 ... >>> print range(10)
1067 ... [0, 1, ..., 9]
1068 ...
1069 ... >>> # should fail: no ellipsis
1070 ... >>> print range(10) # doctest: -ELLIPSIS
1071 ... [0, 1, ..., 9]
1072 ... '''
1073 >>> test = doctest.DocTestFinder().find(f)[0]
1074 >>> doctest.DocTestRunner(verbose=False,
1075 ... optionflags=doctest.ELLIPSIS).run(test)
1076 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001077 Line 6, in f
1078 Failed example:
1079 print range(10) # doctest: -ELLIPSIS
1080 Expected:
1081 [0, 1, ..., 9]
1082 Got:
1083 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001084 (1, 2)
1085
1086Option directives affect only the example that they appear with; they
1087do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001088
Edward Loper74bca7a2004-08-12 02:27:44 +00001089 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001090 ... >>> print range(10) # Should fail: no ellipsis
1091 ... [0, 1, ..., 9]
1092 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001093 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001094 ... [0, 1, ..., 9]
1095 ...
Tim Peters8485b562004-08-04 18:46:34 +00001096 ... >>> print range(10) # Should fail: no ellipsis
1097 ... [0, 1, ..., 9]
1098 ... '''
1099 >>> test = doctest.DocTestFinder().find(f)[0]
1100 >>> doctest.DocTestRunner(verbose=False).run(test)
1101 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001102 Line 2, in f
1103 Failed example:
1104 print range(10) # Should fail: no ellipsis
1105 Expected:
1106 [0, 1, ..., 9]
1107 Got:
1108 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001109 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001110 Line 8, in f
1111 Failed example:
1112 print range(10) # Should fail: no ellipsis
1113 Expected:
1114 [0, 1, ..., 9]
1115 Got:
1116 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001117 (2, 3)
1118
Edward Loper74bca7a2004-08-12 02:27:44 +00001119Multiple options may be modified by a single option directive. They
1120may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001121
1122 >>> def f(x): r'''
1123 ... >>> print range(10) # Should fail
1124 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001125 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001126 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001127 ... [0, 1, ..., 9]
1128 ... '''
1129 >>> test = doctest.DocTestFinder().find(f)[0]
1130 >>> doctest.DocTestRunner(verbose=False).run(test)
1131 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001132 Line 2, in f
1133 Failed example:
1134 print range(10) # Should fail
1135 Expected:
1136 [0, 1, ..., 9]
1137 Got:
1138 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001139 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001140
1141 >>> def f(x): r'''
1142 ... >>> print range(10) # Should fail
1143 ... [0, 1, ..., 9]
1144 ... >>> print range(10) # Should succeed
1145 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1146 ... [0, 1, ..., 9]
1147 ... '''
1148 >>> test = doctest.DocTestFinder().find(f)[0]
1149 >>> doctest.DocTestRunner(verbose=False).run(test)
1150 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001151 Line 2, in f
1152 Failed example:
1153 print range(10) # Should fail
1154 Expected:
1155 [0, 1, ..., 9]
1156 Got:
1157 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001158 (1, 2)
1159
1160 >>> def f(x): r'''
1161 ... >>> print range(10) # Should fail
1162 ... [0, 1, ..., 9]
1163 ... >>> print range(10) # Should succeed
1164 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1165 ... [0, 1, ..., 9]
1166 ... '''
1167 >>> test = doctest.DocTestFinder().find(f)[0]
1168 >>> doctest.DocTestRunner(verbose=False).run(test)
1169 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001170 Line 2, in f
1171 Failed example:
1172 print range(10) # Should fail
1173 Expected:
1174 [0, 1, ..., 9]
1175 Got:
1176 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001177 (1, 2)
1178
1179The option directive may be put on the line following the source, as
1180long as a continuation prompt is used:
1181
1182 >>> def f(x): r'''
1183 ... >>> print range(10)
1184 ... ... # doctest: +ELLIPSIS
1185 ... [0, 1, ..., 9]
1186 ... '''
1187 >>> test = doctest.DocTestFinder().find(f)[0]
1188 >>> doctest.DocTestRunner(verbose=False).run(test)
1189 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001190
Edward Loper74bca7a2004-08-12 02:27:44 +00001191For examples with multi-line source, the option directive may appear
1192at the end of any line:
1193
1194 >>> def f(x): r'''
1195 ... >>> for x in range(10): # doctest: +ELLIPSIS
1196 ... ... print x,
1197 ... 0 1 2 ... 9
1198 ...
1199 ... >>> for x in range(10):
1200 ... ... print x, # doctest: +ELLIPSIS
1201 ... 0 1 2 ... 9
1202 ... '''
1203 >>> test = doctest.DocTestFinder().find(f)[0]
1204 >>> doctest.DocTestRunner(verbose=False).run(test)
1205 (0, 2)
1206
1207If more than one line of an example with multi-line source has an
1208option directive, then they are combined:
1209
1210 >>> def f(x): r'''
1211 ... Should fail (option directive not on the last line):
1212 ... >>> for x in range(10): # doctest: +ELLIPSIS
1213 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1214 ... 0 1 2...9
1215 ... '''
1216 >>> test = doctest.DocTestFinder().find(f)[0]
1217 >>> doctest.DocTestRunner(verbose=False).run(test)
1218 (0, 1)
1219
1220It is an error to have a comment of the form ``# doctest:`` that is
1221*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1222``OPTION`` is an option that has been registered with
1223`register_option`:
1224
1225 >>> # Error: Option not registered
1226 >>> s = '>>> print 12 #doctest: +BADOPTION'
1227 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1228 Traceback (most recent call last):
1229 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1230
1231 >>> # Error: No + or - prefix
1232 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1233 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1234 Traceback (most recent call last):
1235 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1236
1237It is an error to use an option directive on a line that contains no
1238source:
1239
1240 >>> s = '>>> # doctest: +ELLIPSIS'
1241 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1242 Traceback (most recent call last):
1243 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 +00001244"""
1245
1246def test_testsource(): r"""
1247Unit tests for `testsource()`.
1248
1249The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001250test with that name in that module, and converts it to a script. The
1251example code is converted to regular Python code. The surrounding
1252words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001253
1254 >>> import test.test_doctest
1255 >>> name = 'test.test_doctest.sample_func'
1256 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001257 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001258 #
Tim Peters8485b562004-08-04 18:46:34 +00001259 print sample_func(22)
1260 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001261 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001262 #
Edward Lopera5db6002004-08-12 02:41:30 +00001263 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001264
1265 >>> name = 'test.test_doctest.SampleNewStyleClass'
1266 >>> print doctest.testsource(test.test_doctest, name)
1267 print '1\n2\n3'
1268 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001269 ## 1
1270 ## 2
1271 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001272
1273 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1274 >>> print doctest.testsource(test.test_doctest, name)
1275 print SampleClass.a_classmethod(10)
1276 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001277 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001278 print SampleClass(0).a_classmethod(10)
1279 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001280 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001281"""
1282
1283def test_debug(): r"""
1284
1285Create a docstring that we want to debug:
1286
1287 >>> s = '''
1288 ... >>> x = 12
1289 ... >>> print x
1290 ... 12
1291 ... '''
1292
1293Create some fake stdin input, to feed to the debugger:
1294
1295 >>> import tempfile
1296 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1297 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1298 >>> fake_stdin.seek(0)
1299 >>> real_stdin = sys.stdin
1300 >>> sys.stdin = fake_stdin
1301
1302Run the debugger on the docstring, and then restore sys.stdin.
1303
Tim Peters8485b562004-08-04 18:46:34 +00001304 >>> try:
1305 ... doctest.debug_src(s)
1306 ... finally:
1307 ... sys.stdin = real_stdin
1308 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001309 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001310 > <string>(1)?()
1311 (Pdb) 12
1312 --Return--
1313 > <string>(1)?()->None
1314 (Pdb) 12
1315 (Pdb)
1316
1317"""
1318
Jim Fulton356fd192004-08-09 11:34:47 +00001319def test_pdb_set_trace():
1320 r"""Using pdb.set_trace from a doctest
1321
Tim Peters413ced62004-08-09 15:43:47 +00001322 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001323 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001324 you use it. The doctest module changes sys.stdout so that it can
1325 capture program output. It also temporarily replaces pdb.set_trace
1326 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001327 see debugger output.
1328
1329 >>> doc = '''
1330 ... >>> x = 42
1331 ... >>> import pdb; pdb.set_trace()
1332 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001333 >>> parser = doctest.DocTestParser()
1334 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001335 >>> runner = doctest.DocTestRunner(verbose=False)
1336
1337 To demonstrate this, we'll create a fake standard input that
1338 captures our debugger input:
1339
1340 >>> import tempfile
1341 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1342 >>> fake_stdin.write('\n'.join([
1343 ... 'up', # up out of pdb.set_trace
1344 ... 'up', # up again to get out of our wrapper
1345 ... 'print x', # print data defined by the example
1346 ... 'continue', # stop debugging
1347 ... '']))
1348 >>> fake_stdin.seek(0)
1349 >>> real_stdin = sys.stdin
1350 >>> sys.stdin = fake_stdin
1351
Edward Loper74bca7a2004-08-12 02:27:44 +00001352 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001353 --Return--
1354 > ...set_trace()->None
1355 -> Pdb().set_trace()
1356 (Pdb) > ...set_trace()
1357 -> real_pdb_set_trace()
1358 (Pdb) > <string>(1)?()
1359 (Pdb) 42
1360 (Pdb) (0, 2)
1361
1362 >>> sys.stdin = real_stdin
1363 >>> fake_stdin.close()
1364
1365 You can also put pdb.set_trace in a function called from a test:
1366
1367 >>> def calls_set_trace():
1368 ... y=2
1369 ... import pdb; pdb.set_trace()
1370
1371 >>> doc = '''
1372 ... >>> x=1
1373 ... >>> calls_set_trace()
1374 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001375 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001376 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1377 >>> fake_stdin.write('\n'.join([
1378 ... 'up', # up out of pdb.set_trace
1379 ... 'up', # up again to get out of our wrapper
1380 ... 'print y', # print data defined in the function
1381 ... 'up', # out of function
1382 ... 'print x', # print data defined by the example
1383 ... 'continue', # stop debugging
1384 ... '']))
1385 >>> fake_stdin.seek(0)
1386 >>> real_stdin = sys.stdin
1387 >>> sys.stdin = fake_stdin
1388
Edward Loper74bca7a2004-08-12 02:27:44 +00001389 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001390 --Return--
1391 > ...set_trace()->None
1392 -> Pdb().set_trace()
1393 (Pdb) ...set_trace()
1394 -> real_pdb_set_trace()
1395 (Pdb) > <string>(3)calls_set_trace()
1396 (Pdb) 2
1397 (Pdb) > <string>(1)?()
1398 (Pdb) 1
1399 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001400 """
1401
Tim Peters19397e52004-08-06 22:02:59 +00001402def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001403 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001404
1405 We create a Suite by providing a module. A module can be provided
1406 by passing a module object:
1407
1408 >>> import unittest
1409 >>> import test.sample_doctest
1410 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1411 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001412 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001413
1414 We can also supply the module by name:
1415
1416 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1417 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001418 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001419
1420 We can use the current module:
1421
1422 >>> suite = test.sample_doctest.test_suite()
1423 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001424 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001425
1426 We can supply global variables. If we pass globs, they will be
1427 used instead of the module globals. Here we'll pass an empty
1428 globals, triggering an extra error:
1429
1430 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1431 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001432 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001433
1434 Alternatively, we can provide extra globals. Here we'll make an
1435 error go away by providing an extra global variable:
1436
1437 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1438 ... extraglobs={'y': 1})
1439 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001440 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001441
1442 You can pass option flags. Here we'll cause an extra error
1443 by disabling the blank-line feature:
1444
1445 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001446 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001447 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001448 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001449
Tim Peters1e277ee2004-08-07 05:37:52 +00001450 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001451
1452 >>> def setUp():
1453 ... import test.test_doctest
1454 ... test.test_doctest.sillySetup = True
1455
1456 >>> def tearDown():
1457 ... import test.test_doctest
1458 ... del test.test_doctest.sillySetup
1459
1460 Here, we installed a silly variable that the test expects:
1461
1462 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1463 ... setUp=setUp, tearDown=tearDown)
1464 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001465 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001466
1467 But the tearDown restores sanity:
1468
1469 >>> import test.test_doctest
1470 >>> test.test_doctest.sillySetup
1471 Traceback (most recent call last):
1472 ...
1473 AttributeError: 'module' object has no attribute 'sillySetup'
1474
1475 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001476 use a custom test_finder to to run just the test named bar.
1477 However, the test in the module docstring, and the two tests
1478 in the module __test__ dict, aren't filtered, so we actually
1479 run three tests besides bar's. The filtering mechanisms are
1480 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001481
1482 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001483 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001484 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1485 ... test_finder=finder)
1486 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001487 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001488 """
1489
1490def test_DocFileSuite():
1491 """We can test tests found in text files using a DocFileSuite.
1492
1493 We create a suite by providing the names of one or more text
1494 files that include examples:
1495
1496 >>> import unittest
1497 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1498 ... 'test_doctest2.txt')
1499 >>> suite.run(unittest.TestResult())
1500 <unittest.TestResult run=2 errors=0 failures=2>
1501
1502 The test files are looked for in the directory containing the
1503 calling module. A package keyword argument can be provided to
1504 specify a different relative location.
1505
1506 >>> import unittest
1507 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1508 ... 'test_doctest2.txt',
1509 ... package='test')
1510 >>> suite.run(unittest.TestResult())
1511 <unittest.TestResult run=2 errors=0 failures=2>
1512
1513 Note that '/' should be used as a path separator. It will be
1514 converted to a native separator at run time:
1515
1516
1517 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1518 >>> suite.run(unittest.TestResult())
1519 <unittest.TestResult run=1 errors=0 failures=1>
1520
1521 You can specify initial global variables:
1522
1523 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1524 ... 'test_doctest2.txt',
1525 ... globs={'favorite_color': 'blue'})
1526 >>> suite.run(unittest.TestResult())
1527 <unittest.TestResult run=2 errors=0 failures=1>
1528
1529 In this case, we supplied a missing favorite color. You can
1530 provide doctest options:
1531
1532 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1533 ... 'test_doctest2.txt',
1534 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1535 ... globs={'favorite_color': 'blue'})
1536 >>> suite.run(unittest.TestResult())
1537 <unittest.TestResult run=2 errors=0 failures=2>
1538
1539 And, you can provide setUp and tearDown functions:
1540
1541 You can supply setUp and teatDoen functions:
1542
1543 >>> def setUp():
1544 ... import test.test_doctest
1545 ... test.test_doctest.sillySetup = True
1546
1547 >>> def tearDown():
1548 ... import test.test_doctest
1549 ... del test.test_doctest.sillySetup
1550
1551 Here, we installed a silly variable that the test expects:
1552
1553 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1554 ... 'test_doctest2.txt',
1555 ... setUp=setUp, tearDown=tearDown)
1556 >>> suite.run(unittest.TestResult())
1557 <unittest.TestResult run=2 errors=0 failures=1>
1558
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 """
1568
Jim Fulton07a349c2004-08-22 14:10:00 +00001569def test_trailing_space_in_test():
1570 """
Tim Petersa7def722004-08-23 22:13:22 +00001571 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001572
Jim Fulton07a349c2004-08-22 14:10:00 +00001573 >>> x, y = 'foo', ''
1574 >>> print x, y
1575 foo \n
1576 """
Tim Peters19397e52004-08-06 22:02:59 +00001577
Tim Petersa7def722004-08-23 22:13:22 +00001578# old_test1, ... used to live in doctest.py, but cluttered it. Note
1579# that these use the deprecated doctest.Tester, so should go away (or
1580# be rewritten) someday.
1581
1582# Ignore all warnings about the use of class Tester in this module.
1583# Note that the name of this module may differ depending on how it's
1584# imported, so the use of __name__ is important.
1585warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1586 __name__, 0)
1587
1588def old_test1(): r"""
1589>>> from doctest import Tester
1590>>> t = Tester(globs={'x': 42}, verbose=0)
1591>>> t.runstring(r'''
1592... >>> x = x * 2
1593... >>> print x
1594... 42
1595... ''', 'XYZ')
1596**********************************************************************
1597Line 3, in XYZ
1598Failed example:
1599 print x
1600Expected:
1601 42
1602Got:
1603 84
1604(1, 2)
1605>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1606(0, 2)
1607>>> t.summarize()
1608**********************************************************************
16091 items had failures:
1610 1 of 2 in XYZ
1611***Test Failed*** 1 failures.
1612(1, 4)
1613>>> t.summarize(verbose=1)
16141 items passed all tests:
1615 2 tests in example2
1616**********************************************************************
16171 items had failures:
1618 1 of 2 in XYZ
16194 tests in 2 items.
16203 passed and 1 failed.
1621***Test Failed*** 1 failures.
1622(1, 4)
1623"""
1624
1625def old_test2(): r"""
1626 >>> from doctest import Tester
1627 >>> t = Tester(globs={}, verbose=1)
1628 >>> test = r'''
1629 ... # just an example
1630 ... >>> x = 1 + 2
1631 ... >>> x
1632 ... 3
1633 ... '''
1634 >>> t.runstring(test, "Example")
1635 Running string Example
1636 Trying: x = 1 + 2
1637 Expecting: nothing
1638 ok
1639 Trying: x
1640 Expecting: 3
1641 ok
1642 0 of 2 examples failed in string Example
1643 (0, 2)
1644"""
1645
1646def old_test3(): r"""
1647 >>> from doctest import Tester
1648 >>> t = Tester(globs={}, verbose=0)
1649 >>> def _f():
1650 ... '''Trivial docstring example.
1651 ... >>> assert 2 == 2
1652 ... '''
1653 ... return 32
1654 ...
1655 >>> t.rundoc(_f) # expect 0 failures in 1 example
1656 (0, 1)
1657"""
1658
1659def old_test4(): """
1660 >>> import new
1661 >>> m1 = new.module('_m1')
1662 >>> m2 = new.module('_m2')
1663 >>> test_data = \"""
1664 ... def _f():
1665 ... '''>>> assert 1 == 1
1666 ... '''
1667 ... def g():
1668 ... '''>>> assert 2 != 1
1669 ... '''
1670 ... class H:
1671 ... '''>>> assert 2 > 1
1672 ... '''
1673 ... def bar(self):
1674 ... '''>>> assert 1 < 2
1675 ... '''
1676 ... \"""
1677 >>> exec test_data in m1.__dict__
1678 >>> exec test_data in m2.__dict__
1679 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
1680
1681 Tests that objects outside m1 are excluded:
1682
1683 >>> from doctest import Tester
1684 >>> t = Tester(globs={}, verbose=0)
1685 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
1686 (0, 4)
1687
1688 Once more, not excluding stuff outside m1:
1689
1690 >>> t = Tester(globs={}, verbose=0)
1691 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
1692 (0, 8)
1693
1694 The exclusion of objects from outside the designated module is
1695 meant to be invoked automagically by testmod.
1696
1697 >>> doctest.testmod(m1, verbose=False)
1698 (0, 4)
1699"""
1700
Tim Peters8485b562004-08-04 18:46:34 +00001701######################################################################
1702## Main
1703######################################################################
1704
1705def test_main():
1706 # Check the doctest cases in doctest itself:
1707 test_support.run_doctest(doctest, verbosity=True)
1708 # Check the doctest cases defined here:
1709 from test import test_doctest
1710 test_support.run_doctest(test_doctest, verbosity=True)
1711
1712import trace, sys, re, StringIO
1713def test_coverage(coverdir):
1714 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1715 trace=0, count=1)
1716 tracer.run('reload(doctest); test_main()')
1717 r = tracer.results()
1718 print 'Writing coverage results...'
1719 r.write_results(show_missing=True, summary=True,
1720 coverdir=coverdir)
1721
1722if __name__ == '__main__':
1723 if '-c' in sys.argv:
1724 test_coverage('/tmp/doctest.cover')
1725 else:
1726 test_main()