blob: 5d0cf90be5a07ee91bbb9888de51a84b66153fae [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
126Example is a simple container class that holds a source code string,
127an expected output string, and a line number (within the docstring):
128
129 >>> example = doctest.Example('print 1', '1\n', 0)
130 >>> (example.source, example.want, example.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000131 ('print 1\n', '1\n', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000132
Tim Petersbb431472004-08-09 03:51:46 +0000133The `source` string ends in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000134
Tim Petersbb431472004-08-09 03:51:46 +0000135 Source spans a single line: no terminating newline.
Tim Peters8485b562004-08-04 18:46:34 +0000136 >>> e = doctest.Example('print 1', '1\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000137 >>> e.source, e.want
138 ('print 1\n', '1\n')
139
Tim Peters8485b562004-08-04 18:46:34 +0000140 >>> e = doctest.Example('print 1\n', '1\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000141 >>> e.source, e.want
142 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000143
Tim Petersbb431472004-08-09 03:51:46 +0000144 Source spans multiple lines: require terminating newline.
Tim Peters8485b562004-08-04 18:46:34 +0000145 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000146 >>> e.source, e.want
147 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000148
Tim Petersbb431472004-08-09 03:51:46 +0000149 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n', 0)
150 >>> e.source, e.want
151 ('print 1;\nprint 2\n', '1\n2\n')
152
153The `want` string ends with a newline, unless it's the empty string:
Tim Peters8485b562004-08-04 18:46:34 +0000154
155 >>> e = doctest.Example('print 1', '1\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000156 >>> e.source, e.want
157 ('print 1\n', '1\n')
158
Tim Peters8485b562004-08-04 18:46:34 +0000159 >>> e = doctest.Example('print 1', '1', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000160 >>> e.source, e.want
161 ('print 1\n', '1\n')
162
Tim Peters8485b562004-08-04 18:46:34 +0000163 >>> e = doctest.Example('print', '', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000164 >>> e.source, e.want
165 ('print\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000166"""
167
168def test_DocTest(): r"""
169Unit tests for the `DocTest` class.
170
171DocTest is a collection of examples, extracted from a docstring, along
172with information about where the docstring comes from (a name,
173filename, and line number). The docstring is parsed by the `DocTest`
174constructor:
175
176 >>> docstring = '''
177 ... >>> print 12
178 ... 12
179 ...
180 ... Non-example text.
181 ...
182 ... >>> print 'another\example'
183 ... another
184 ... example
185 ... '''
186 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000187 >>> parser = doctest.DocTestParser()
188 >>> test = parser.get_doctest(docstring, globs, 'some_test',
189 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000190 >>> print test
191 <DocTest some_test from some_file:20 (2 examples)>
192 >>> len(test.examples)
193 2
194 >>> e1, e2 = test.examples
195 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000196 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000197 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000198 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000199
200Source information (name, filename, and line number) is available as
201attributes on the doctest object:
202
203 >>> (test.name, test.filename, test.lineno)
204 ('some_test', 'some_file', 20)
205
206The line number of an example within its containing file is found by
207adding the line number of the example and the line number of its
208containing test:
209
210 >>> test.lineno + e1.lineno
211 21
212 >>> test.lineno + e2.lineno
213 26
214
215If the docstring contains inconsistant leading whitespace in the
216expected output of an example, then `DocTest` will raise a ValueError:
217
218 >>> docstring = r'''
219 ... >>> print 'bad\nindentation'
220 ... bad
221 ... indentation
222 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000223 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000224 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000225 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: ' indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000226
227If the docstring contains inconsistent leading whitespace on
228continuation lines, then `DocTest` will raise a ValueError:
229
230 >>> docstring = r'''
231 ... >>> print ('bad indentation',
232 ... ... 2)
233 ... ('bad', 'indentation')
234 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000235 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000236 Traceback (most recent call last):
237 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: ' ... 2)'
238
239If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
240will raise a ValueError:
241
242 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000243 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000244 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000245 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
246
247If there's no blank space after a PS2 prompt ('...'), then `DocTest`
248will raise a ValueError:
249
250 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000251 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000252 Traceback (most recent call last):
253 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
254
Tim Peters8485b562004-08-04 18:46:34 +0000255"""
256
Tim Peters8485b562004-08-04 18:46:34 +0000257def test_DocTestFinder(): r"""
258Unit tests for the `DocTestFinder` class.
259
260DocTestFinder is used to extract DocTests from an object's docstring
261and the docstrings of its contained objects. It can be used with
262modules, functions, classes, methods, staticmethods, classmethods, and
263properties.
264
265Finding Tests in Functions
266~~~~~~~~~~~~~~~~~~~~~~~~~~
267For a function whose docstring contains examples, DocTestFinder.find()
268will return a single test (for that function's docstring):
269
Tim Peters8485b562004-08-04 18:46:34 +0000270 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000271
272We'll simulate a __file__ attr that ends in pyc:
273
274 >>> import test.test_doctest
275 >>> old = test.test_doctest.__file__
276 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
277
Tim Peters8485b562004-08-04 18:46:34 +0000278 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000279
Edward Loper74bca7a2004-08-12 02:27:44 +0000280 >>> print tests # doctest: +ELLIPSIS
Tim Petersa7def722004-08-23 22:13:22 +0000281 [<DocTest sample_func from ...:13 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000282
Tim Peters4de7c5c2004-08-23 22:38:05 +0000283The exact name depends on how test_doctest was invoked, so allow for
284leading path components.
285
286 >>> tests[0].filename # doctest: +ELLIPSIS
287 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000288
289 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000290
Jim Fulton07a349c2004-08-22 14:10:00 +0000291
Tim Peters8485b562004-08-04 18:46:34 +0000292 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000293 >>> (e.source, e.want, e.lineno)
294 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000295
Tim Peters8485b562004-08-04 18:46:34 +0000296If an object has no docstring, then a test is not created for it:
297
298 >>> def no_docstring(v):
299 ... pass
300 >>> finder.find(no_docstring)
301 []
302
303If the function has a docstring with no examples, then a test with no
304examples is returned. (This lets `DocTestRunner` collect statistics
305about which functions have no tests -- but is that useful? And should
306an empty test also be created when there's no docstring?)
307
308 >>> def no_examples(v):
309 ... ''' no doctest examples '''
310 >>> finder.find(no_examples)
311 [<DocTest no_examples from None:1 (no examples)>]
312
313Finding Tests in Classes
314~~~~~~~~~~~~~~~~~~~~~~~~
315For a class, DocTestFinder will create a test for the class's
316docstring, and will recursively explore its contents, including
317methods, classmethods, staticmethods, properties, and nested classes.
318
319 >>> finder = doctest.DocTestFinder()
320 >>> tests = finder.find(SampleClass)
321 >>> tests.sort()
322 >>> for t in tests:
323 ... print '%2s %s' % (len(t.examples), t.name)
324 1 SampleClass
325 3 SampleClass.NestedClass
326 1 SampleClass.NestedClass.__init__
327 1 SampleClass.__init__
328 2 SampleClass.a_classmethod
329 1 SampleClass.a_property
330 1 SampleClass.a_staticmethod
331 1 SampleClass.double
332 1 SampleClass.get
333
334New-style classes are also supported:
335
336 >>> tests = finder.find(SampleNewStyleClass)
337 >>> tests.sort()
338 >>> for t in tests:
339 ... print '%2s %s' % (len(t.examples), t.name)
340 1 SampleNewStyleClass
341 1 SampleNewStyleClass.__init__
342 1 SampleNewStyleClass.double
343 1 SampleNewStyleClass.get
344
345Finding Tests in Modules
346~~~~~~~~~~~~~~~~~~~~~~~~
347For a module, DocTestFinder will create a test for the class's
348docstring, and will recursively explore its contents, including
349functions, classes, and the `__test__` dictionary, if it exists:
350
351 >>> # A module
352 >>> import new
353 >>> m = new.module('some_module')
354 >>> def triple(val):
355 ... '''
356 ... >>> print tripple(11)
357 ... 33
358 ... '''
359 ... return val*3
360 >>> m.__dict__.update({
361 ... 'sample_func': sample_func,
362 ... 'SampleClass': SampleClass,
363 ... '__doc__': '''
364 ... Module docstring.
365 ... >>> print 'module'
366 ... module
367 ... ''',
368 ... '__test__': {
369 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
370 ... 'c': triple}})
371
372 >>> finder = doctest.DocTestFinder()
373 >>> # Use module=test.test_doctest, to prevent doctest from
374 >>> # ignoring the objects since they weren't defined in m.
375 >>> import test.test_doctest
376 >>> tests = finder.find(m, module=test.test_doctest)
377 >>> tests.sort()
378 >>> for t in tests:
379 ... print '%2s %s' % (len(t.examples), t.name)
380 1 some_module
381 1 some_module.SampleClass
382 3 some_module.SampleClass.NestedClass
383 1 some_module.SampleClass.NestedClass.__init__
384 1 some_module.SampleClass.__init__
385 2 some_module.SampleClass.a_classmethod
386 1 some_module.SampleClass.a_property
387 1 some_module.SampleClass.a_staticmethod
388 1 some_module.SampleClass.double
389 1 some_module.SampleClass.get
390 1 some_module.c
391 2 some_module.d
392 1 some_module.sample_func
393
394Duplicate Removal
395~~~~~~~~~~~~~~~~~
396If a single object is listed twice (under different names), then tests
397will only be generated for it once:
398
Tim Petersf3f57472004-08-08 06:11:48 +0000399 >>> from test import doctest_aliases
400 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000401 >>> tests.sort()
402 >>> print len(tests)
403 2
404 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000405 test.doctest_aliases.TwoNames
406
407 TwoNames.f and TwoNames.g are bound to the same object.
408 We can't guess which will be found in doctest's traversal of
409 TwoNames.__dict__ first, so we have to allow for either.
410
411 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000412 True
413
414Filter Functions
415~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000416A filter function can be used to restrict which objects get examined,
417but this is temporary, undocumented internal support for testmod's
418deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000419
420 >>> def namefilter(prefix, base):
421 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000422 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000423 >>> tests.sort()
424 >>> for t in tests:
425 ... print '%2s %s' % (len(t.examples), t.name)
426 1 SampleClass
427 3 SampleClass.NestedClass
428 1 SampleClass.NestedClass.__init__
429 1 SampleClass.__init__
430 1 SampleClass.double
431 1 SampleClass.get
432
Tim Peters8485b562004-08-04 18:46:34 +0000433If a given object is filtered out, then none of the objects that it
434contains will be added either:
435
436 >>> def namefilter(prefix, base):
437 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000438 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000439 >>> tests.sort()
440 >>> for t in tests:
441 ... print '%2s %s' % (len(t.examples), t.name)
442 1 SampleClass
443 1 SampleClass.__init__
444 2 SampleClass.a_classmethod
445 1 SampleClass.a_property
446 1 SampleClass.a_staticmethod
447 1 SampleClass.double
448 1 SampleClass.get
449
Tim Petersf727c6c2004-08-08 01:48:59 +0000450The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000451object explicitly passed to DocTestFinder:
452
453 >>> def namefilter(prefix, base):
454 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000455 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000456 >>> len(tests)
457 9
458
459Turning off Recursion
460~~~~~~~~~~~~~~~~~~~~~
461DocTestFinder can be told not to look for tests in contained objects
462using the `recurse` flag:
463
464 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
465 >>> tests.sort()
466 >>> for t in tests:
467 ... print '%2s %s' % (len(t.examples), t.name)
468 1 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000469
470Line numbers
471~~~~~~~~~~~~
472DocTestFinder finds the line number of each example:
473
474 >>> def f(x):
475 ... '''
476 ... >>> x = 12
477 ...
478 ... some text
479 ...
480 ... >>> # examples are not created for comments & bare prompts.
481 ... >>>
482 ... ...
483 ...
484 ... >>> for x in range(10):
485 ... ... print x,
486 ... 0 1 2 3 4 5 6 7 8 9
487 ... >>> x/2
488 ... 6
489 ... '''
490 >>> test = doctest.DocTestFinder().find(f)[0]
491 >>> [e.lineno for e in test.examples]
492 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000493"""
494
495class test_DocTestRunner:
496 def basics(): r"""
497Unit tests for the `DocTestRunner` class.
498
499DocTestRunner is used to run DocTest test cases, and to accumulate
500statistics. Here's a simple DocTest case we can use:
501
502 >>> def f(x):
503 ... '''
504 ... >>> x = 12
505 ... >>> print x
506 ... 12
507 ... >>> x/2
508 ... 6
509 ... '''
510 >>> test = doctest.DocTestFinder().find(f)[0]
511
512The main DocTestRunner interface is the `run` method, which runs a
513given DocTest case in a given namespace (globs). It returns a tuple
514`(f,t)`, where `f` is the number of failed tests and `t` is the number
515of tried tests.
516
517 >>> doctest.DocTestRunner(verbose=False).run(test)
518 (0, 3)
519
520If any example produces incorrect output, then the test runner reports
521the failure and proceeds to the next example:
522
523 >>> def f(x):
524 ... '''
525 ... >>> x = 12
526 ... >>> print x
527 ... 14
528 ... >>> x/2
529 ... 6
530 ... '''
531 >>> test = doctest.DocTestFinder().find(f)[0]
532 >>> doctest.DocTestRunner(verbose=True).run(test)
533 Trying: x = 12
534 Expecting: nothing
535 ok
536 Trying: print x
537 Expecting: 14
538 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000539 Line 3, in f
540 Failed example:
541 print x
542 Expected:
543 14
544 Got:
545 12
Tim Peters8485b562004-08-04 18:46:34 +0000546 Trying: x/2
547 Expecting: 6
548 ok
549 (1, 3)
550"""
551 def verbose_flag(): r"""
552The `verbose` flag makes the test runner generate more detailed
553output:
554
555 >>> def f(x):
556 ... '''
557 ... >>> x = 12
558 ... >>> print x
559 ... 12
560 ... >>> x/2
561 ... 6
562 ... '''
563 >>> test = doctest.DocTestFinder().find(f)[0]
564
565 >>> doctest.DocTestRunner(verbose=True).run(test)
566 Trying: x = 12
567 Expecting: nothing
568 ok
569 Trying: print x
570 Expecting: 12
571 ok
572 Trying: x/2
573 Expecting: 6
574 ok
575 (0, 3)
576
577If the `verbose` flag is unspecified, then the output will be verbose
578iff `-v` appears in sys.argv:
579
580 >>> # Save the real sys.argv list.
581 >>> old_argv = sys.argv
582
583 >>> # If -v does not appear in sys.argv, then output isn't verbose.
584 >>> sys.argv = ['test']
585 >>> doctest.DocTestRunner().run(test)
586 (0, 3)
587
588 >>> # If -v does appear in sys.argv, then output is verbose.
589 >>> sys.argv = ['test', '-v']
590 >>> doctest.DocTestRunner().run(test)
591 Trying: x = 12
592 Expecting: nothing
593 ok
594 Trying: print x
595 Expecting: 12
596 ok
597 Trying: x/2
598 Expecting: 6
599 ok
600 (0, 3)
601
602 >>> # Restore sys.argv
603 >>> sys.argv = old_argv
604
605In the remaining examples, the test runner's verbosity will be
606explicitly set, to ensure that the test behavior is consistent.
607 """
608 def exceptions(): r"""
609Tests of `DocTestRunner`'s exception handling.
610
611An expected exception is specified with a traceback message. The
612lines between the first line and the type/value may be omitted or
613replaced with any other string:
614
615 >>> def f(x):
616 ... '''
617 ... >>> x = 12
618 ... >>> print x/0
619 ... Traceback (most recent call last):
620 ... ZeroDivisionError: integer division or modulo by zero
621 ... '''
622 >>> test = doctest.DocTestFinder().find(f)[0]
623 >>> doctest.DocTestRunner(verbose=False).run(test)
624 (0, 2)
625
Edward Loper19b19582004-08-25 23:07:03 +0000626An example may not generate output before it raises an exception; if
627it does, then the traceback message will not be recognized as
628signaling an expected exception, so the example will be reported as an
629unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000630
631 >>> def f(x):
632 ... '''
633 ... >>> x = 12
634 ... >>> print 'pre-exception output', x/0
635 ... pre-exception output
636 ... Traceback (most recent call last):
637 ... ZeroDivisionError: integer division or modulo by zero
638 ... '''
639 >>> test = doctest.DocTestFinder().find(f)[0]
640 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000641 ... # doctest: +ELLIPSIS
642 **********************************************************************
643 Line 3, in f
644 Failed example:
645 print 'pre-exception output', x/0
646 Exception raised:
647 ...
648 ZeroDivisionError: integer division or modulo by zero
649 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000650
651Exception messages may contain newlines:
652
653 >>> def f(x):
654 ... r'''
655 ... >>> raise ValueError, 'multi\nline\nmessage'
656 ... Traceback (most recent call last):
657 ... ValueError: multi
658 ... line
659 ... message
660 ... '''
661 >>> test = doctest.DocTestFinder().find(f)[0]
662 >>> doctest.DocTestRunner(verbose=False).run(test)
663 (0, 1)
664
665If an exception is expected, but an exception with the wrong type or
666message is raised, then it is reported as a failure:
667
668 >>> def f(x):
669 ... r'''
670 ... >>> raise ValueError, 'message'
671 ... Traceback (most recent call last):
672 ... ValueError: wrong message
673 ... '''
674 >>> test = doctest.DocTestFinder().find(f)[0]
675 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000676 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000677 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000678 Line 2, in f
679 Failed example:
680 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000681 Expected:
682 Traceback (most recent call last):
683 ValueError: wrong message
684 Got:
685 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000686 ...
Tim Peters8485b562004-08-04 18:46:34 +0000687 ValueError: message
688 (1, 1)
689
690If an exception is raised but not expected, then it is reported as an
691unexpected exception:
692
Tim Peters8485b562004-08-04 18:46:34 +0000693 >>> def f(x):
694 ... r'''
695 ... >>> 1/0
696 ... 0
697 ... '''
698 >>> test = doctest.DocTestFinder().find(f)[0]
699 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000700 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000701 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000702 Line 2, in f
703 Failed example:
704 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000705 Exception raised:
706 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000707 ...
Tim Peters8485b562004-08-04 18:46:34 +0000708 ZeroDivisionError: integer division or modulo by zero
709 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000710"""
711 def optionflags(): r"""
712Tests of `DocTestRunner`'s option flag handling.
713
714Several option flags can be used to customize the behavior of the test
715runner. These are defined as module constants in doctest, and passed
716to the DocTestRunner constructor (multiple constants should be or-ed
717together).
718
719The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
720and 1/0:
721
722 >>> def f(x):
723 ... '>>> True\n1\n'
724
725 >>> # Without the flag:
726 >>> test = doctest.DocTestFinder().find(f)[0]
727 >>> doctest.DocTestRunner(verbose=False).run(test)
728 (0, 1)
729
730 >>> # With the flag:
731 >>> test = doctest.DocTestFinder().find(f)[0]
732 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
733 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
734 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000735 Line 1, in f
736 Failed example:
737 True
738 Expected:
739 1
740 Got:
741 True
Tim Peters8485b562004-08-04 18:46:34 +0000742 (1, 1)
743
744The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
745and the '<BLANKLINE>' marker:
746
747 >>> def f(x):
748 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
749
750 >>> # Without the flag:
751 >>> test = doctest.DocTestFinder().find(f)[0]
752 >>> doctest.DocTestRunner(verbose=False).run(test)
753 (0, 1)
754
755 >>> # With the flag:
756 >>> test = doctest.DocTestFinder().find(f)[0]
757 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
758 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
759 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000760 Line 1, in f
761 Failed example:
762 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000763 Expected:
764 a
765 <BLANKLINE>
766 b
767 Got:
768 a
769 <BLANKLINE>
770 b
771 (1, 1)
772
773The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
774treated as equal:
775
776 >>> def f(x):
777 ... '>>> print 1, 2, 3\n 1 2\n 3'
778
779 >>> # Without the flag:
780 >>> test = doctest.DocTestFinder().find(f)[0]
781 >>> doctest.DocTestRunner(verbose=False).run(test)
782 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000783 Line 1, in f
784 Failed example:
785 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000786 Expected:
787 1 2
788 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000789 Got:
790 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000791 (1, 1)
792
793 >>> # With the flag:
794 >>> test = doctest.DocTestFinder().find(f)[0]
795 >>> flags = doctest.NORMALIZE_WHITESPACE
796 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
797 (0, 1)
798
Tim Peters026f8dc2004-08-19 16:38:58 +0000799 An example from the docs:
800 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
801 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
802 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
803
Tim Peters8485b562004-08-04 18:46:34 +0000804The ELLIPSIS flag causes ellipsis marker ("...") in the expected
805output to match any substring in the actual output:
806
807 >>> def f(x):
808 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
809
810 >>> # Without the flag:
811 >>> test = doctest.DocTestFinder().find(f)[0]
812 >>> doctest.DocTestRunner(verbose=False).run(test)
813 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000814 Line 1, in f
815 Failed example:
816 print range(15)
817 Expected:
818 [0, 1, 2, ..., 14]
819 Got:
820 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +0000821 (1, 1)
822
823 >>> # With the flag:
824 >>> test = doctest.DocTestFinder().find(f)[0]
825 >>> flags = doctest.ELLIPSIS
826 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
827 (0, 1)
828
Tim Peterse594bee2004-08-22 01:47:51 +0000829 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +0000830
831 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +0000832 ... print i**2, #doctest: +ELLIPSIS
833 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +0000834
Tim Peters026f8dc2004-08-19 16:38:58 +0000835 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000836
837 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +0000838 ... print i,
839 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +0000840
Tim Peters026f8dc2004-08-19 16:38:58 +0000841 Examples from the docs:
842
843 >>> print range(20) # doctest:+ELLIPSIS
844 [0, 1, ..., 18, 19]
845
846 >>> print range(20) # doctest: +ELLIPSIS
847 ... # doctest: +NORMALIZE_WHITESPACE
848 [0, 1, ..., 18, 19]
849
Tim Peters8485b562004-08-04 18:46:34 +0000850The UNIFIED_DIFF flag causes failures that involve multi-line expected
851and actual outputs to be displayed using a unified diff:
852
853 >>> def f(x):
854 ... r'''
855 ... >>> print '\n'.join('abcdefg')
856 ... a
857 ... B
858 ... c
859 ... d
860 ... f
861 ... g
862 ... h
863 ... '''
864
865 >>> # Without the flag:
866 >>> test = doctest.DocTestFinder().find(f)[0]
867 >>> doctest.DocTestRunner(verbose=False).run(test)
868 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000869 Line 2, in f
870 Failed example:
871 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000872 Expected:
873 a
874 B
875 c
876 d
877 f
878 g
879 h
880 Got:
881 a
882 b
883 c
884 d
885 e
886 f
887 g
888 (1, 1)
889
890 >>> # With the flag:
891 >>> test = doctest.DocTestFinder().find(f)[0]
892 >>> flags = doctest.UNIFIED_DIFF
893 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
894 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000895 Line 2, in f
896 Failed example:
897 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000898 Differences (unified diff):
899 --- Expected
900 +++ Got
901 @@ -1,8 +1,8 @@
902 a
903 -B
904 +b
905 c
906 d
907 +e
908 f
909 g
910 -h
911 <BLANKLINE>
912 (1, 1)
913
914The CONTEXT_DIFF flag causes failures that involve multi-line expected
915and actual outputs to be displayed using a context diff:
916
917 >>> # Reuse f() from the UNIFIED_DIFF example, above.
918 >>> test = doctest.DocTestFinder().find(f)[0]
919 >>> flags = doctest.CONTEXT_DIFF
920 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
921 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000922 Line 2, in f
923 Failed example:
924 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000925 Differences (context diff):
926 *** Expected
927 --- Got
928 ***************
929 *** 1,8 ****
930 a
931 ! B
932 c
933 d
934 f
935 g
936 - h
937 <BLANKLINE>
938 --- 1,8 ----
939 a
940 ! b
941 c
942 d
943 + e
944 f
945 g
946 <BLANKLINE>
947 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +0000948
949
950The NDIFF_DIFF flag causes failures to use the difflib.Differ algorithm
951used by the popular ndiff.py utility. This does intraline difference
952marking, as well as interline differences.
953
954 >>> def f(x):
955 ... r'''
956 ... >>> print "a b c d e f g h i j k l m"
957 ... a b c d e f g h i j k 1 m
958 ... '''
959 >>> test = doctest.DocTestFinder().find(f)[0]
960 >>> flags = doctest.NDIFF_DIFF
961 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
962 **********************************************************************
963 Line 2, in f
964 Failed example:
965 print "a b c d e f g h i j k l m"
966 Differences (ndiff with -expected +actual):
967 - a b c d e f g h i j k 1 m
968 ? ^
969 + a b c d e f g h i j k l m
970 ? + ++ ^
971 <BLANKLINE>
972 (1, 1)
973 """
974
Tim Peters8485b562004-08-04 18:46:34 +0000975 def option_directives(): r"""
976Tests of `DocTestRunner`'s option directive mechanism.
977
Edward Loper74bca7a2004-08-12 02:27:44 +0000978Option directives can be used to turn option flags on or off for a
979single example. To turn an option on for an example, follow that
980example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +0000981
982 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +0000983 ... >>> print range(10) # should fail: no ellipsis
984 ... [0, 1, ..., 9]
985 ...
986 ... >>> print range(10) # doctest: +ELLIPSIS
987 ... [0, 1, ..., 9]
988 ... '''
989 >>> test = doctest.DocTestFinder().find(f)[0]
990 >>> doctest.DocTestRunner(verbose=False).run(test)
991 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000992 Line 2, in f
993 Failed example:
994 print range(10) # should fail: no ellipsis
995 Expected:
996 [0, 1, ..., 9]
997 Got:
998 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +0000999 (1, 2)
1000
1001To turn an option off for an example, follow that example with a
1002comment of the form ``# doctest: -OPTION``:
1003
1004 >>> def f(x): r'''
1005 ... >>> print range(10)
1006 ... [0, 1, ..., 9]
1007 ...
1008 ... >>> # should fail: no ellipsis
1009 ... >>> print range(10) # doctest: -ELLIPSIS
1010 ... [0, 1, ..., 9]
1011 ... '''
1012 >>> test = doctest.DocTestFinder().find(f)[0]
1013 >>> doctest.DocTestRunner(verbose=False,
1014 ... optionflags=doctest.ELLIPSIS).run(test)
1015 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001016 Line 6, in f
1017 Failed example:
1018 print range(10) # doctest: -ELLIPSIS
1019 Expected:
1020 [0, 1, ..., 9]
1021 Got:
1022 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001023 (1, 2)
1024
1025Option directives affect only the example that they appear with; they
1026do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001027
Edward Loper74bca7a2004-08-12 02:27:44 +00001028 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001029 ... >>> print range(10) # Should fail: no ellipsis
1030 ... [0, 1, ..., 9]
1031 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001032 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001033 ... [0, 1, ..., 9]
1034 ...
Tim Peters8485b562004-08-04 18:46:34 +00001035 ... >>> print range(10) # Should fail: no ellipsis
1036 ... [0, 1, ..., 9]
1037 ... '''
1038 >>> test = doctest.DocTestFinder().find(f)[0]
1039 >>> doctest.DocTestRunner(verbose=False).run(test)
1040 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001041 Line 2, in f
1042 Failed example:
1043 print range(10) # Should fail: no ellipsis
1044 Expected:
1045 [0, 1, ..., 9]
1046 Got:
1047 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001048 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001049 Line 8, in f
1050 Failed example:
1051 print range(10) # Should fail: no ellipsis
1052 Expected:
1053 [0, 1, ..., 9]
1054 Got:
1055 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001056 (2, 3)
1057
Edward Loper74bca7a2004-08-12 02:27:44 +00001058Multiple options may be modified by a single option directive. They
1059may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001060
1061 >>> def f(x): r'''
1062 ... >>> print range(10) # Should fail
1063 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001064 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001065 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001066 ... [0, 1, ..., 9]
1067 ... '''
1068 >>> test = doctest.DocTestFinder().find(f)[0]
1069 >>> doctest.DocTestRunner(verbose=False).run(test)
1070 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001071 Line 2, in f
1072 Failed example:
1073 print range(10) # Should fail
1074 Expected:
1075 [0, 1, ..., 9]
1076 Got:
1077 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001078 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001079
1080 >>> def f(x): r'''
1081 ... >>> print range(10) # Should fail
1082 ... [0, 1, ..., 9]
1083 ... >>> print range(10) # Should succeed
1084 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1085 ... [0, 1, ..., 9]
1086 ... '''
1087 >>> test = doctest.DocTestFinder().find(f)[0]
1088 >>> doctest.DocTestRunner(verbose=False).run(test)
1089 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001090 Line 2, in f
1091 Failed example:
1092 print range(10) # Should fail
1093 Expected:
1094 [0, 1, ..., 9]
1095 Got:
1096 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001097 (1, 2)
1098
1099 >>> def f(x): r'''
1100 ... >>> print range(10) # Should fail
1101 ... [0, 1, ..., 9]
1102 ... >>> print range(10) # Should succeed
1103 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1104 ... [0, 1, ..., 9]
1105 ... '''
1106 >>> test = doctest.DocTestFinder().find(f)[0]
1107 >>> doctest.DocTestRunner(verbose=False).run(test)
1108 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001109 Line 2, in f
1110 Failed example:
1111 print range(10) # Should fail
1112 Expected:
1113 [0, 1, ..., 9]
1114 Got:
1115 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001116 (1, 2)
1117
1118The option directive may be put on the line following the source, as
1119long as a continuation prompt is used:
1120
1121 >>> def f(x): r'''
1122 ... >>> print range(10)
1123 ... ... # doctest: +ELLIPSIS
1124 ... [0, 1, ..., 9]
1125 ... '''
1126 >>> test = doctest.DocTestFinder().find(f)[0]
1127 >>> doctest.DocTestRunner(verbose=False).run(test)
1128 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001129
Edward Loper74bca7a2004-08-12 02:27:44 +00001130For examples with multi-line source, the option directive may appear
1131at the end of any line:
1132
1133 >>> def f(x): r'''
1134 ... >>> for x in range(10): # doctest: +ELLIPSIS
1135 ... ... print x,
1136 ... 0 1 2 ... 9
1137 ...
1138 ... >>> for x in range(10):
1139 ... ... print x, # doctest: +ELLIPSIS
1140 ... 0 1 2 ... 9
1141 ... '''
1142 >>> test = doctest.DocTestFinder().find(f)[0]
1143 >>> doctest.DocTestRunner(verbose=False).run(test)
1144 (0, 2)
1145
1146If more than one line of an example with multi-line source has an
1147option directive, then they are combined:
1148
1149 >>> def f(x): r'''
1150 ... Should fail (option directive not on the last line):
1151 ... >>> for x in range(10): # doctest: +ELLIPSIS
1152 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1153 ... 0 1 2...9
1154 ... '''
1155 >>> test = doctest.DocTestFinder().find(f)[0]
1156 >>> doctest.DocTestRunner(verbose=False).run(test)
1157 (0, 1)
1158
1159It is an error to have a comment of the form ``# doctest:`` that is
1160*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1161``OPTION`` is an option that has been registered with
1162`register_option`:
1163
1164 >>> # Error: Option not registered
1165 >>> s = '>>> print 12 #doctest: +BADOPTION'
1166 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1167 Traceback (most recent call last):
1168 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1169
1170 >>> # Error: No + or - prefix
1171 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1172 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1173 Traceback (most recent call last):
1174 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1175
1176It is an error to use an option directive on a line that contains no
1177source:
1178
1179 >>> s = '>>> # doctest: +ELLIPSIS'
1180 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1181 Traceback (most recent call last):
1182 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 +00001183"""
1184
1185def test_testsource(): r"""
1186Unit tests for `testsource()`.
1187
1188The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001189test with that name in that module, and converts it to a script. The
1190example code is converted to regular Python code. The surrounding
1191words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001192
1193 >>> import test.test_doctest
1194 >>> name = 'test.test_doctest.sample_func'
1195 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001196 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001197 #
Tim Peters8485b562004-08-04 18:46:34 +00001198 print sample_func(22)
1199 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001200 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001201 #
Edward Lopera5db6002004-08-12 02:41:30 +00001202 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001203
1204 >>> name = 'test.test_doctest.SampleNewStyleClass'
1205 >>> print doctest.testsource(test.test_doctest, name)
1206 print '1\n2\n3'
1207 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001208 ## 1
1209 ## 2
1210 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001211
1212 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1213 >>> print doctest.testsource(test.test_doctest, name)
1214 print SampleClass.a_classmethod(10)
1215 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001216 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001217 print SampleClass(0).a_classmethod(10)
1218 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001219 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001220"""
1221
1222def test_debug(): r"""
1223
1224Create a docstring that we want to debug:
1225
1226 >>> s = '''
1227 ... >>> x = 12
1228 ... >>> print x
1229 ... 12
1230 ... '''
1231
1232Create some fake stdin input, to feed to the debugger:
1233
1234 >>> import tempfile
1235 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1236 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1237 >>> fake_stdin.seek(0)
1238 >>> real_stdin = sys.stdin
1239 >>> sys.stdin = fake_stdin
1240
1241Run the debugger on the docstring, and then restore sys.stdin.
1242
Tim Peters8485b562004-08-04 18:46:34 +00001243 >>> try:
1244 ... doctest.debug_src(s)
1245 ... finally:
1246 ... sys.stdin = real_stdin
1247 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001248 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001249 > <string>(1)?()
1250 (Pdb) 12
1251 --Return--
1252 > <string>(1)?()->None
1253 (Pdb) 12
1254 (Pdb)
1255
1256"""
1257
Jim Fulton356fd192004-08-09 11:34:47 +00001258def test_pdb_set_trace():
1259 r"""Using pdb.set_trace from a doctest
1260
Tim Peters413ced62004-08-09 15:43:47 +00001261 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001262 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001263 you use it. The doctest module changes sys.stdout so that it can
1264 capture program output. It also temporarily replaces pdb.set_trace
1265 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001266 see debugger output.
1267
1268 >>> doc = '''
1269 ... >>> x = 42
1270 ... >>> import pdb; pdb.set_trace()
1271 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001272 >>> parser = doctest.DocTestParser()
1273 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001274 >>> runner = doctest.DocTestRunner(verbose=False)
1275
1276 To demonstrate this, we'll create a fake standard input that
1277 captures our debugger input:
1278
1279 >>> import tempfile
1280 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1281 >>> fake_stdin.write('\n'.join([
1282 ... 'up', # up out of pdb.set_trace
1283 ... 'up', # up again to get out of our wrapper
1284 ... 'print x', # print data defined by the example
1285 ... 'continue', # stop debugging
1286 ... '']))
1287 >>> fake_stdin.seek(0)
1288 >>> real_stdin = sys.stdin
1289 >>> sys.stdin = fake_stdin
1290
Edward Loper74bca7a2004-08-12 02:27:44 +00001291 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001292 --Return--
1293 > ...set_trace()->None
1294 -> Pdb().set_trace()
1295 (Pdb) > ...set_trace()
1296 -> real_pdb_set_trace()
1297 (Pdb) > <string>(1)?()
1298 (Pdb) 42
1299 (Pdb) (0, 2)
1300
1301 >>> sys.stdin = real_stdin
1302 >>> fake_stdin.close()
1303
1304 You can also put pdb.set_trace in a function called from a test:
1305
1306 >>> def calls_set_trace():
1307 ... y=2
1308 ... import pdb; pdb.set_trace()
1309
1310 >>> doc = '''
1311 ... >>> x=1
1312 ... >>> calls_set_trace()
1313 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001314 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001315 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1316 >>> fake_stdin.write('\n'.join([
1317 ... 'up', # up out of pdb.set_trace
1318 ... 'up', # up again to get out of our wrapper
1319 ... 'print y', # print data defined in the function
1320 ... 'up', # out of function
1321 ... 'print x', # print data defined by the example
1322 ... 'continue', # stop debugging
1323 ... '']))
1324 >>> fake_stdin.seek(0)
1325 >>> real_stdin = sys.stdin
1326 >>> sys.stdin = fake_stdin
1327
Edward Loper74bca7a2004-08-12 02:27:44 +00001328 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001329 --Return--
1330 > ...set_trace()->None
1331 -> Pdb().set_trace()
1332 (Pdb) ...set_trace()
1333 -> real_pdb_set_trace()
1334 (Pdb) > <string>(3)calls_set_trace()
1335 (Pdb) 2
1336 (Pdb) > <string>(1)?()
1337 (Pdb) 1
1338 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001339 """
1340
Tim Peters19397e52004-08-06 22:02:59 +00001341def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001342 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001343
1344 We create a Suite by providing a module. A module can be provided
1345 by passing a module object:
1346
1347 >>> import unittest
1348 >>> import test.sample_doctest
1349 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1350 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001351 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001352
1353 We can also supply the module by name:
1354
1355 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1356 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001357 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001358
1359 We can use the current module:
1360
1361 >>> suite = test.sample_doctest.test_suite()
1362 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001363 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001364
1365 We can supply global variables. If we pass globs, they will be
1366 used instead of the module globals. Here we'll pass an empty
1367 globals, triggering an extra error:
1368
1369 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1370 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001371 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001372
1373 Alternatively, we can provide extra globals. Here we'll make an
1374 error go away by providing an extra global variable:
1375
1376 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1377 ... extraglobs={'y': 1})
1378 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001379 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001380
1381 You can pass option flags. Here we'll cause an extra error
1382 by disabling the blank-line feature:
1383
1384 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001385 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001386 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001387 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001388
Tim Peters1e277ee2004-08-07 05:37:52 +00001389 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001390
1391 >>> def setUp():
1392 ... import test.test_doctest
1393 ... test.test_doctest.sillySetup = True
1394
1395 >>> def tearDown():
1396 ... import test.test_doctest
1397 ... del test.test_doctest.sillySetup
1398
1399 Here, we installed a silly variable that the test expects:
1400
1401 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1402 ... setUp=setUp, tearDown=tearDown)
1403 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001404 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001405
1406 But the tearDown restores sanity:
1407
1408 >>> import test.test_doctest
1409 >>> test.test_doctest.sillySetup
1410 Traceback (most recent call last):
1411 ...
1412 AttributeError: 'module' object has no attribute 'sillySetup'
1413
1414 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001415 use a custom test_finder to to run just the test named bar.
1416 However, the test in the module docstring, and the two tests
1417 in the module __test__ dict, aren't filtered, so we actually
1418 run three tests besides bar's. The filtering mechanisms are
1419 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001420
1421 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001422 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001423 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1424 ... test_finder=finder)
1425 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001426 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001427 """
1428
1429def test_DocFileSuite():
1430 """We can test tests found in text files using a DocFileSuite.
1431
1432 We create a suite by providing the names of one or more text
1433 files that include examples:
1434
1435 >>> import unittest
1436 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1437 ... 'test_doctest2.txt')
1438 >>> suite.run(unittest.TestResult())
1439 <unittest.TestResult run=2 errors=0 failures=2>
1440
1441 The test files are looked for in the directory containing the
1442 calling module. A package keyword argument can be provided to
1443 specify a different relative location.
1444
1445 >>> import unittest
1446 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1447 ... 'test_doctest2.txt',
1448 ... package='test')
1449 >>> suite.run(unittest.TestResult())
1450 <unittest.TestResult run=2 errors=0 failures=2>
1451
1452 Note that '/' should be used as a path separator. It will be
1453 converted to a native separator at run time:
1454
1455
1456 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1457 >>> suite.run(unittest.TestResult())
1458 <unittest.TestResult run=1 errors=0 failures=1>
1459
1460 You can specify initial global variables:
1461
1462 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1463 ... 'test_doctest2.txt',
1464 ... globs={'favorite_color': 'blue'})
1465 >>> suite.run(unittest.TestResult())
1466 <unittest.TestResult run=2 errors=0 failures=1>
1467
1468 In this case, we supplied a missing favorite color. You can
1469 provide doctest options:
1470
1471 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1472 ... 'test_doctest2.txt',
1473 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1474 ... globs={'favorite_color': 'blue'})
1475 >>> suite.run(unittest.TestResult())
1476 <unittest.TestResult run=2 errors=0 failures=2>
1477
1478 And, you can provide setUp and tearDown functions:
1479
1480 You can supply setUp and teatDoen functions:
1481
1482 >>> def setUp():
1483 ... import test.test_doctest
1484 ... test.test_doctest.sillySetup = True
1485
1486 >>> def tearDown():
1487 ... import test.test_doctest
1488 ... del test.test_doctest.sillySetup
1489
1490 Here, we installed a silly variable that the test expects:
1491
1492 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1493 ... 'test_doctest2.txt',
1494 ... setUp=setUp, tearDown=tearDown)
1495 >>> suite.run(unittest.TestResult())
1496 <unittest.TestResult run=2 errors=0 failures=1>
1497
1498 But the tearDown restores sanity:
1499
1500 >>> import test.test_doctest
1501 >>> test.test_doctest.sillySetup
1502 Traceback (most recent call last):
1503 ...
1504 AttributeError: 'module' object has no attribute 'sillySetup'
1505
1506 """
1507
Jim Fulton07a349c2004-08-22 14:10:00 +00001508def test_trailing_space_in_test():
1509 """
Tim Petersa7def722004-08-23 22:13:22 +00001510 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001511
Jim Fulton07a349c2004-08-22 14:10:00 +00001512 >>> x, y = 'foo', ''
1513 >>> print x, y
1514 foo \n
1515 """
Tim Peters19397e52004-08-06 22:02:59 +00001516
Tim Petersa7def722004-08-23 22:13:22 +00001517# old_test1, ... used to live in doctest.py, but cluttered it. Note
1518# that these use the deprecated doctest.Tester, so should go away (or
1519# be rewritten) someday.
1520
1521# Ignore all warnings about the use of class Tester in this module.
1522# Note that the name of this module may differ depending on how it's
1523# imported, so the use of __name__ is important.
1524warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1525 __name__, 0)
1526
1527def old_test1(): r"""
1528>>> from doctest import Tester
1529>>> t = Tester(globs={'x': 42}, verbose=0)
1530>>> t.runstring(r'''
1531... >>> x = x * 2
1532... >>> print x
1533... 42
1534... ''', 'XYZ')
1535**********************************************************************
1536Line 3, in XYZ
1537Failed example:
1538 print x
1539Expected:
1540 42
1541Got:
1542 84
1543(1, 2)
1544>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1545(0, 2)
1546>>> t.summarize()
1547**********************************************************************
15481 items had failures:
1549 1 of 2 in XYZ
1550***Test Failed*** 1 failures.
1551(1, 4)
1552>>> t.summarize(verbose=1)
15531 items passed all tests:
1554 2 tests in example2
1555**********************************************************************
15561 items had failures:
1557 1 of 2 in XYZ
15584 tests in 2 items.
15593 passed and 1 failed.
1560***Test Failed*** 1 failures.
1561(1, 4)
1562"""
1563
1564def old_test2(): r"""
1565 >>> from doctest import Tester
1566 >>> t = Tester(globs={}, verbose=1)
1567 >>> test = r'''
1568 ... # just an example
1569 ... >>> x = 1 + 2
1570 ... >>> x
1571 ... 3
1572 ... '''
1573 >>> t.runstring(test, "Example")
1574 Running string Example
1575 Trying: x = 1 + 2
1576 Expecting: nothing
1577 ok
1578 Trying: x
1579 Expecting: 3
1580 ok
1581 0 of 2 examples failed in string Example
1582 (0, 2)
1583"""
1584
1585def old_test3(): r"""
1586 >>> from doctest import Tester
1587 >>> t = Tester(globs={}, verbose=0)
1588 >>> def _f():
1589 ... '''Trivial docstring example.
1590 ... >>> assert 2 == 2
1591 ... '''
1592 ... return 32
1593 ...
1594 >>> t.rundoc(_f) # expect 0 failures in 1 example
1595 (0, 1)
1596"""
1597
1598def old_test4(): """
1599 >>> import new
1600 >>> m1 = new.module('_m1')
1601 >>> m2 = new.module('_m2')
1602 >>> test_data = \"""
1603 ... def _f():
1604 ... '''>>> assert 1 == 1
1605 ... '''
1606 ... def g():
1607 ... '''>>> assert 2 != 1
1608 ... '''
1609 ... class H:
1610 ... '''>>> assert 2 > 1
1611 ... '''
1612 ... def bar(self):
1613 ... '''>>> assert 1 < 2
1614 ... '''
1615 ... \"""
1616 >>> exec test_data in m1.__dict__
1617 >>> exec test_data in m2.__dict__
1618 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
1619
1620 Tests that objects outside m1 are excluded:
1621
1622 >>> from doctest import Tester
1623 >>> t = Tester(globs={}, verbose=0)
1624 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
1625 (0, 4)
1626
1627 Once more, not excluding stuff outside m1:
1628
1629 >>> t = Tester(globs={}, verbose=0)
1630 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
1631 (0, 8)
1632
1633 The exclusion of objects from outside the designated module is
1634 meant to be invoked automagically by testmod.
1635
1636 >>> doctest.testmod(m1, verbose=False)
1637 (0, 4)
1638"""
1639
Tim Peters8485b562004-08-04 18:46:34 +00001640######################################################################
1641## Main
1642######################################################################
1643
1644def test_main():
1645 # Check the doctest cases in doctest itself:
1646 test_support.run_doctest(doctest, verbosity=True)
1647 # Check the doctest cases defined here:
1648 from test import test_doctest
1649 test_support.run_doctest(test_doctest, verbosity=True)
1650
1651import trace, sys, re, StringIO
1652def test_coverage(coverdir):
1653 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1654 trace=0, count=1)
1655 tracer.run('reload(doctest); test_main()')
1656 r = tracer.results()
1657 print 'Writing coverage results...'
1658 r.write_results(show_missing=True, summary=True,
1659 coverdir=coverdir)
1660
1661if __name__ == '__main__':
1662 if '-c' in sys.argv:
1663 test_coverage('/tmp/doctest.cover')
1664 else:
1665 test_main()