blob: aae93c46c910eecfedaf3780dce92c310679dc43 [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
7
8######################################################################
9## Sample Objects (used by test cases)
10######################################################################
11
12def sample_func(v):
13 """
Tim Peters19397e52004-08-06 22:02:59 +000014 Blah blah
15
Tim Peters8485b562004-08-04 18:46:34 +000016 >>> print sample_func(22)
17 44
Tim Peters19397e52004-08-06 22:02:59 +000018
19 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000020 """
21 return v+v
22
23class SampleClass:
24 """
25 >>> print 1
26 1
27 """
28 def __init__(self, val):
29 """
30 >>> print SampleClass(12).get()
31 12
32 """
33 self.val = val
34
35 def double(self):
36 """
37 >>> print SampleClass(12).double().get()
38 24
39 """
40 return SampleClass(self.val + self.val)
41
42 def get(self):
43 """
44 >>> print SampleClass(-5).get()
45 -5
46 """
47 return self.val
48
49 def a_staticmethod(v):
50 """
51 >>> print SampleClass.a_staticmethod(10)
52 11
53 """
54 return v+1
55 a_staticmethod = staticmethod(a_staticmethod)
56
57 def a_classmethod(cls, v):
58 """
59 >>> print SampleClass.a_classmethod(10)
60 12
61 >>> print SampleClass(0).a_classmethod(10)
62 12
63 """
64 return v+2
65 a_classmethod = classmethod(a_classmethod)
66
67 a_property = property(get, doc="""
68 >>> print SampleClass(22).a_property
69 22
70 """)
71
72 class NestedClass:
73 """
74 >>> x = SampleClass.NestedClass(5)
75 >>> y = x.square()
76 >>> print y.get()
77 25
78 """
79 def __init__(self, val=0):
80 """
81 >>> print SampleClass.NestedClass().get()
82 0
83 """
84 self.val = val
85 def square(self):
86 return SampleClass.NestedClass(self.val*self.val)
87 def get(self):
88 return self.val
89
90class SampleNewStyleClass(object):
91 r"""
92 >>> print '1\n2\n3'
93 1
94 2
95 3
96 """
97 def __init__(self, val):
98 """
99 >>> print SampleNewStyleClass(12).get()
100 12
101 """
102 self.val = val
103
104 def double(self):
105 """
106 >>> print SampleNewStyleClass(12).double().get()
107 24
108 """
109 return SampleNewStyleClass(self.val + self.val)
110
111 def get(self):
112 """
113 >>> print SampleNewStyleClass(-5).get()
114 -5
115 """
116 return self.val
117
118######################################################################
119## Test Cases
120######################################################################
121
122def test_Example(): r"""
123Unit tests for the `Example` class.
124
125Example is a simple container class that holds a source code string,
126an expected output string, and a line number (within the docstring):
127
128 >>> example = doctest.Example('print 1', '1\n', 0)
129 >>> (example.source, example.want, example.lineno)
130 ('print 1', '1\n', 0)
131
132The `source` string should end in a newline iff the source spans more
133than one line:
134
135 >>> # Source spans a single line: no terminating newline.
136 >>> e = doctest.Example('print 1', '1\n', 0)
137 >>> e = doctest.Example('print 1\n', '1\n', 0)
138 Traceback (most recent call last):
Tim Peters9b625d32004-08-04 20:04:32 +0000139 AssertionError: source must end with newline iff source contains more than one line
Tim Peters8485b562004-08-04 18:46:34 +0000140
141 >>> # Source spans multiple lines: require terminating newline.
142 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n', 0)
143 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n', 0)
144 Traceback (most recent call last):
Tim Peters9b625d32004-08-04 20:04:32 +0000145 AssertionError: source must end with newline iff source contains more than one line
Tim Peters8485b562004-08-04 18:46:34 +0000146
147The `want` string should be terminated by a newline, unless it's the
148empty string:
149
150 >>> e = doctest.Example('print 1', '1\n', 0)
151 >>> e = doctest.Example('print 1', '1', 0)
152 Traceback (most recent call last):
Tim Peters9b625d32004-08-04 20:04:32 +0000153 AssertionError: non-empty want must end with newline
Tim Peters8485b562004-08-04 18:46:34 +0000154 >>> e = doctest.Example('print', '', 0)
155"""
156
157def test_DocTest(): r"""
158Unit tests for the `DocTest` class.
159
160DocTest is a collection of examples, extracted from a docstring, along
161with information about where the docstring comes from (a name,
162filename, and line number). The docstring is parsed by the `DocTest`
163constructor:
164
165 >>> docstring = '''
166 ... >>> print 12
167 ... 12
168 ...
169 ... Non-example text.
170 ...
171 ... >>> print 'another\example'
172 ... another
173 ... example
174 ... '''
175 >>> globs = {} # globals to run the test in.
176 >>> test = doctest.DocTest(docstring, globs, 'some_test', 'some_file', 20)
177 >>> print test
178 <DocTest some_test from some_file:20 (2 examples)>
179 >>> len(test.examples)
180 2
181 >>> e1, e2 = test.examples
182 >>> (e1.source, e1.want, e1.lineno)
183 ('print 12', '12\n', 1)
184 >>> (e2.source, e2.want, e2.lineno)
185 ("print 'another\\example'", 'another\nexample\n', 6)
186
187Source information (name, filename, and line number) is available as
188attributes on the doctest object:
189
190 >>> (test.name, test.filename, test.lineno)
191 ('some_test', 'some_file', 20)
192
193The line number of an example within its containing file is found by
194adding the line number of the example and the line number of its
195containing test:
196
197 >>> test.lineno + e1.lineno
198 21
199 >>> test.lineno + e2.lineno
200 26
201
202If the docstring contains inconsistant leading whitespace in the
203expected output of an example, then `DocTest` will raise a ValueError:
204
205 >>> docstring = r'''
206 ... >>> print 'bad\nindentation'
207 ... bad
208 ... indentation
209 ... '''
210 >>> doctest.DocTest(docstring, globs, 'some_test', 'filename', 0)
211 Traceback (most recent call last):
212 ValueError: line 3 of the docstring for some_test has inconsistent leading whitespace: ' indentation'
213
214If the docstring contains inconsistent leading whitespace on
215continuation lines, then `DocTest` will raise a ValueError:
216
217 >>> docstring = r'''
218 ... >>> print ('bad indentation',
219 ... ... 2)
220 ... ('bad', 'indentation')
221 ... '''
222 >>> doctest.DocTest(docstring, globs, 'some_test', 'filename', 0)
223 Traceback (most recent call last):
224 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: ' ... 2)'
225
226If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
227will raise a ValueError:
228
229 >>> docstring = '>>>print 1\n1'
230 >>> doctest.DocTest(docstring, globs, 'some_test', 'filename', 0)
231 Traceback (most recent call last):
232 ValueError: line 0 of the docstring for some_test lacks blank after >>>: '>>>print 1'
233"""
234
235# [XX] test that it's getting line numbers right.
236def test_DocTestFinder(): r"""
237Unit tests for the `DocTestFinder` class.
238
239DocTestFinder is used to extract DocTests from an object's docstring
240and the docstrings of its contained objects. It can be used with
241modules, functions, classes, methods, staticmethods, classmethods, and
242properties.
243
244Finding Tests in Functions
245~~~~~~~~~~~~~~~~~~~~~~~~~~
246For a function whose docstring contains examples, DocTestFinder.find()
247will return a single test (for that function's docstring):
248
249 >>> # Allow ellipsis in the following examples (since the filename
250 >>> # and line number in the traceback can vary):
251 >>> doctest: +ELLIPSIS
252
253 >>> finder = doctest.DocTestFinder()
254 >>> tests = finder.find(sample_func)
255 >>> print tests
256 [<DocTest sample_func from ...:12 (1 example)>]
257 >>> e = tests[0].examples[0]
258 >>> print (e.source, e.want, e.lineno)
Tim Peters19397e52004-08-06 22:02:59 +0000259 ('print sample_func(22)', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000260
261 >>> doctest: -ELLIPSIS # Turn ellipsis back off
262
263If an object has no docstring, then a test is not created for it:
264
265 >>> def no_docstring(v):
266 ... pass
267 >>> finder.find(no_docstring)
268 []
269
270If the function has a docstring with no examples, then a test with no
271examples is returned. (This lets `DocTestRunner` collect statistics
272about which functions have no tests -- but is that useful? And should
273an empty test also be created when there's no docstring?)
274
275 >>> def no_examples(v):
276 ... ''' no doctest examples '''
277 >>> finder.find(no_examples)
278 [<DocTest no_examples from None:1 (no examples)>]
279
280Finding Tests in Classes
281~~~~~~~~~~~~~~~~~~~~~~~~
282For a class, DocTestFinder will create a test for the class's
283docstring, and will recursively explore its contents, including
284methods, classmethods, staticmethods, properties, and nested classes.
285
286 >>> finder = doctest.DocTestFinder()
287 >>> tests = finder.find(SampleClass)
288 >>> tests.sort()
289 >>> for t in tests:
290 ... print '%2s %s' % (len(t.examples), t.name)
291 1 SampleClass
292 3 SampleClass.NestedClass
293 1 SampleClass.NestedClass.__init__
294 1 SampleClass.__init__
295 2 SampleClass.a_classmethod
296 1 SampleClass.a_property
297 1 SampleClass.a_staticmethod
298 1 SampleClass.double
299 1 SampleClass.get
300
301New-style classes are also supported:
302
303 >>> tests = finder.find(SampleNewStyleClass)
304 >>> tests.sort()
305 >>> for t in tests:
306 ... print '%2s %s' % (len(t.examples), t.name)
307 1 SampleNewStyleClass
308 1 SampleNewStyleClass.__init__
309 1 SampleNewStyleClass.double
310 1 SampleNewStyleClass.get
311
312Finding Tests in Modules
313~~~~~~~~~~~~~~~~~~~~~~~~
314For a module, DocTestFinder will create a test for the class's
315docstring, and will recursively explore its contents, including
316functions, classes, and the `__test__` dictionary, if it exists:
317
318 >>> # A module
319 >>> import new
320 >>> m = new.module('some_module')
321 >>> def triple(val):
322 ... '''
323 ... >>> print tripple(11)
324 ... 33
325 ... '''
326 ... return val*3
327 >>> m.__dict__.update({
328 ... 'sample_func': sample_func,
329 ... 'SampleClass': SampleClass,
330 ... '__doc__': '''
331 ... Module docstring.
332 ... >>> print 'module'
333 ... module
334 ... ''',
335 ... '__test__': {
336 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
337 ... 'c': triple}})
338
339 >>> finder = doctest.DocTestFinder()
340 >>> # Use module=test.test_doctest, to prevent doctest from
341 >>> # ignoring the objects since they weren't defined in m.
342 >>> import test.test_doctest
343 >>> tests = finder.find(m, module=test.test_doctest)
344 >>> tests.sort()
345 >>> for t in tests:
346 ... print '%2s %s' % (len(t.examples), t.name)
347 1 some_module
348 1 some_module.SampleClass
349 3 some_module.SampleClass.NestedClass
350 1 some_module.SampleClass.NestedClass.__init__
351 1 some_module.SampleClass.__init__
352 2 some_module.SampleClass.a_classmethod
353 1 some_module.SampleClass.a_property
354 1 some_module.SampleClass.a_staticmethod
355 1 some_module.SampleClass.double
356 1 some_module.SampleClass.get
357 1 some_module.c
358 2 some_module.d
359 1 some_module.sample_func
360
361Duplicate Removal
362~~~~~~~~~~~~~~~~~
363If a single object is listed twice (under different names), then tests
364will only be generated for it once:
365
Tim Petersf3f57472004-08-08 06:11:48 +0000366 >>> from test import doctest_aliases
367 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000368 >>> tests.sort()
369 >>> print len(tests)
370 2
371 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000372 test.doctest_aliases.TwoNames
373
374 TwoNames.f and TwoNames.g are bound to the same object.
375 We can't guess which will be found in doctest's traversal of
376 TwoNames.__dict__ first, so we have to allow for either.
377
378 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000379 True
380
381Filter Functions
382~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000383A filter function can be used to restrict which objects get examined,
384but this is temporary, undocumented internal support for testmod's
385deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000386
387 >>> def namefilter(prefix, base):
388 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000389 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000390 >>> tests.sort()
391 >>> for t in tests:
392 ... print '%2s %s' % (len(t.examples), t.name)
393 1 SampleClass
394 3 SampleClass.NestedClass
395 1 SampleClass.NestedClass.__init__
396 1 SampleClass.__init__
397 1 SampleClass.double
398 1 SampleClass.get
399
Tim Peters8485b562004-08-04 18:46:34 +0000400If a given object is filtered out, then none of the objects that it
401contains will be added either:
402
403 >>> def namefilter(prefix, base):
404 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000405 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000406 >>> tests.sort()
407 >>> for t in tests:
408 ... print '%2s %s' % (len(t.examples), t.name)
409 1 SampleClass
410 1 SampleClass.__init__
411 2 SampleClass.a_classmethod
412 1 SampleClass.a_property
413 1 SampleClass.a_staticmethod
414 1 SampleClass.double
415 1 SampleClass.get
416
Tim Petersf727c6c2004-08-08 01:48:59 +0000417The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000418object explicitly passed to DocTestFinder:
419
420 >>> def namefilter(prefix, base):
421 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000422 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000423 >>> len(tests)
424 9
425
426Turning off Recursion
427~~~~~~~~~~~~~~~~~~~~~
428DocTestFinder can be told not to look for tests in contained objects
429using the `recurse` flag:
430
431 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
432 >>> tests.sort()
433 >>> for t in tests:
434 ... print '%2s %s' % (len(t.examples), t.name)
435 1 SampleClass
436"""
437
438class test_DocTestRunner:
439 def basics(): r"""
440Unit tests for the `DocTestRunner` class.
441
442DocTestRunner is used to run DocTest test cases, and to accumulate
443statistics. Here's a simple DocTest case we can use:
444
445 >>> def f(x):
446 ... '''
447 ... >>> x = 12
448 ... >>> print x
449 ... 12
450 ... >>> x/2
451 ... 6
452 ... '''
453 >>> test = doctest.DocTestFinder().find(f)[0]
454
455The main DocTestRunner interface is the `run` method, which runs a
456given DocTest case in a given namespace (globs). It returns a tuple
457`(f,t)`, where `f` is the number of failed tests and `t` is the number
458of tried tests.
459
460 >>> doctest.DocTestRunner(verbose=False).run(test)
461 (0, 3)
462
463If any example produces incorrect output, then the test runner reports
464the failure and proceeds to the next example:
465
466 >>> def f(x):
467 ... '''
468 ... >>> x = 12
469 ... >>> print x
470 ... 14
471 ... >>> x/2
472 ... 6
473 ... '''
474 >>> test = doctest.DocTestFinder().find(f)[0]
475 >>> doctest.DocTestRunner(verbose=True).run(test)
476 Trying: x = 12
477 Expecting: nothing
478 ok
479 Trying: print x
480 Expecting: 14
481 **********************************************************************
482 Failure in example: print x
483 from line #2 of f
484 Expected: 14
485 Got: 12
486 Trying: x/2
487 Expecting: 6
488 ok
489 (1, 3)
490"""
491 def verbose_flag(): r"""
492The `verbose` flag makes the test runner generate more detailed
493output:
494
495 >>> def f(x):
496 ... '''
497 ... >>> x = 12
498 ... >>> print x
499 ... 12
500 ... >>> x/2
501 ... 6
502 ... '''
503 >>> test = doctest.DocTestFinder().find(f)[0]
504
505 >>> doctest.DocTestRunner(verbose=True).run(test)
506 Trying: x = 12
507 Expecting: nothing
508 ok
509 Trying: print x
510 Expecting: 12
511 ok
512 Trying: x/2
513 Expecting: 6
514 ok
515 (0, 3)
516
517If the `verbose` flag is unspecified, then the output will be verbose
518iff `-v` appears in sys.argv:
519
520 >>> # Save the real sys.argv list.
521 >>> old_argv = sys.argv
522
523 >>> # If -v does not appear in sys.argv, then output isn't verbose.
524 >>> sys.argv = ['test']
525 >>> doctest.DocTestRunner().run(test)
526 (0, 3)
527
528 >>> # If -v does appear in sys.argv, then output is verbose.
529 >>> sys.argv = ['test', '-v']
530 >>> doctest.DocTestRunner().run(test)
531 Trying: x = 12
532 Expecting: nothing
533 ok
534 Trying: print x
535 Expecting: 12
536 ok
537 Trying: x/2
538 Expecting: 6
539 ok
540 (0, 3)
541
542 >>> # Restore sys.argv
543 >>> sys.argv = old_argv
544
545In the remaining examples, the test runner's verbosity will be
546explicitly set, to ensure that the test behavior is consistent.
547 """
548 def exceptions(): r"""
549Tests of `DocTestRunner`'s exception handling.
550
551An expected exception is specified with a traceback message. The
552lines between the first line and the type/value may be omitted or
553replaced with any other string:
554
555 >>> def f(x):
556 ... '''
557 ... >>> x = 12
558 ... >>> print x/0
559 ... Traceback (most recent call last):
560 ... ZeroDivisionError: integer division or modulo by zero
561 ... '''
562 >>> test = doctest.DocTestFinder().find(f)[0]
563 >>> doctest.DocTestRunner(verbose=False).run(test)
564 (0, 2)
565
566An example may generate output before it raises an exception; if it
567does, then the output must match the expected output:
568
569 >>> def f(x):
570 ... '''
571 ... >>> x = 12
572 ... >>> print 'pre-exception output', x/0
573 ... pre-exception output
574 ... Traceback (most recent call last):
575 ... ZeroDivisionError: integer division or modulo by zero
576 ... '''
577 >>> test = doctest.DocTestFinder().find(f)[0]
578 >>> doctest.DocTestRunner(verbose=False).run(test)
579 (0, 2)
580
581Exception messages may contain newlines:
582
583 >>> def f(x):
584 ... r'''
585 ... >>> raise ValueError, 'multi\nline\nmessage'
586 ... Traceback (most recent call last):
587 ... ValueError: multi
588 ... line
589 ... message
590 ... '''
591 >>> test = doctest.DocTestFinder().find(f)[0]
592 >>> doctest.DocTestRunner(verbose=False).run(test)
593 (0, 1)
594
595If an exception is expected, but an exception with the wrong type or
596message is raised, then it is reported as a failure:
597
598 >>> def f(x):
599 ... r'''
600 ... >>> raise ValueError, 'message'
601 ... Traceback (most recent call last):
602 ... ValueError: wrong message
603 ... '''
604 >>> test = doctest.DocTestFinder().find(f)[0]
605 >>> doctest.DocTestRunner(verbose=False).run(test)
606 **********************************************************************
607 Failure in example: raise ValueError, 'message'
608 from line #1 of f
609 Expected:
610 Traceback (most recent call last):
611 ValueError: wrong message
612 Got:
613 Traceback (most recent call last):
614 ValueError: message
615 (1, 1)
616
617If an exception is raised but not expected, then it is reported as an
618unexpected exception:
619
620 >>> # Allow ellipsis in the following examples (since the filename
621 >>> # and line number in the traceback can vary):
622 >>> doctest: +ELLIPSIS
623
624 >>> def f(x):
625 ... r'''
626 ... >>> 1/0
627 ... 0
628 ... '''
629 >>> test = doctest.DocTestFinder().find(f)[0]
630 >>> doctest.DocTestRunner(verbose=False).run(test)
631 **********************************************************************
632 Failure in example: 1/0
633 from line #1 of f
634 Exception raised:
635 Traceback (most recent call last):
636 ...
637 ZeroDivisionError: integer division or modulo by zero
638 (1, 1)
639
640 >>> doctest: -ELLIPSIS # Turn ellipsis back off:
641"""
642 def optionflags(): r"""
643Tests of `DocTestRunner`'s option flag handling.
644
645Several option flags can be used to customize the behavior of the test
646runner. These are defined as module constants in doctest, and passed
647to the DocTestRunner constructor (multiple constants should be or-ed
648together).
649
650The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
651and 1/0:
652
653 >>> def f(x):
654 ... '>>> True\n1\n'
655
656 >>> # Without the flag:
657 >>> test = doctest.DocTestFinder().find(f)[0]
658 >>> doctest.DocTestRunner(verbose=False).run(test)
659 (0, 1)
660
661 >>> # With the flag:
662 >>> test = doctest.DocTestFinder().find(f)[0]
663 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
664 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
665 **********************************************************************
666 Failure in example: True
667 from line #0 of f
668 Expected: 1
669 Got: True
670 (1, 1)
671
672The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
673and the '<BLANKLINE>' marker:
674
675 >>> def f(x):
676 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
677
678 >>> # Without the flag:
679 >>> test = doctest.DocTestFinder().find(f)[0]
680 >>> doctest.DocTestRunner(verbose=False).run(test)
681 (0, 1)
682
683 >>> # With the flag:
684 >>> test = doctest.DocTestFinder().find(f)[0]
685 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
686 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
687 **********************************************************************
688 Failure in example: print "a\n\nb"
689 from line #0 of f
690 Expected:
691 a
692 <BLANKLINE>
693 b
694 Got:
695 a
696 <BLANKLINE>
697 b
698 (1, 1)
699
700The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
701treated as equal:
702
703 >>> def f(x):
704 ... '>>> print 1, 2, 3\n 1 2\n 3'
705
706 >>> # Without the flag:
707 >>> test = doctest.DocTestFinder().find(f)[0]
708 >>> doctest.DocTestRunner(verbose=False).run(test)
709 **********************************************************************
710 Failure in example: print 1, 2, 3
711 from line #0 of f
712 Expected:
713 1 2
714 3
715 Got: 1 2 3
716 (1, 1)
717
718 >>> # With the flag:
719 >>> test = doctest.DocTestFinder().find(f)[0]
720 >>> flags = doctest.NORMALIZE_WHITESPACE
721 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
722 (0, 1)
723
724The ELLIPSIS flag causes ellipsis marker ("...") in the expected
725output to match any substring in the actual output:
726
727 >>> def f(x):
728 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
729
730 >>> # Without the flag:
731 >>> test = doctest.DocTestFinder().find(f)[0]
732 >>> doctest.DocTestRunner(verbose=False).run(test)
733 **********************************************************************
734 Failure in example: print range(15)
735 from line #0 of f
736 Expected: [0, 1, 2, ..., 14]
737 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
738 (1, 1)
739
740 >>> # With the flag:
741 >>> test = doctest.DocTestFinder().find(f)[0]
742 >>> flags = doctest.ELLIPSIS
743 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
744 (0, 1)
745
746The UNIFIED_DIFF flag causes failures that involve multi-line expected
747and actual outputs to be displayed using a unified diff:
748
749 >>> def f(x):
750 ... r'''
751 ... >>> print '\n'.join('abcdefg')
752 ... a
753 ... B
754 ... c
755 ... d
756 ... f
757 ... g
758 ... h
759 ... '''
760
761 >>> # Without the flag:
762 >>> test = doctest.DocTestFinder().find(f)[0]
763 >>> doctest.DocTestRunner(verbose=False).run(test)
764 **********************************************************************
765 Failure in example: print '\n'.join('abcdefg')
766 from line #1 of f
767 Expected:
768 a
769 B
770 c
771 d
772 f
773 g
774 h
775 Got:
776 a
777 b
778 c
779 d
780 e
781 f
782 g
783 (1, 1)
784
785 >>> # With the flag:
786 >>> test = doctest.DocTestFinder().find(f)[0]
787 >>> flags = doctest.UNIFIED_DIFF
788 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
789 **********************************************************************
790 Failure in example: print '\n'.join('abcdefg')
791 from line #1 of f
792 Differences (unified diff):
793 --- Expected
794 +++ Got
795 @@ -1,8 +1,8 @@
796 a
797 -B
798 +b
799 c
800 d
801 +e
802 f
803 g
804 -h
805 <BLANKLINE>
806 (1, 1)
807
808The CONTEXT_DIFF flag causes failures that involve multi-line expected
809and actual outputs to be displayed using a context diff:
810
811 >>> # Reuse f() from the UNIFIED_DIFF example, above.
812 >>> test = doctest.DocTestFinder().find(f)[0]
813 >>> flags = doctest.CONTEXT_DIFF
814 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
815 **********************************************************************
816 Failure in example: print '\n'.join('abcdefg')
817 from line #1 of f
818 Differences (context diff):
819 *** Expected
820 --- Got
821 ***************
822 *** 1,8 ****
823 a
824 ! B
825 c
826 d
827 f
828 g
829 - h
830 <BLANKLINE>
831 --- 1,8 ----
832 a
833 ! b
834 c
835 d
836 + e
837 f
838 g
839 <BLANKLINE>
840 (1, 1)
841"""
842 def option_directives(): r"""
843Tests of `DocTestRunner`'s option directive mechanism.
844
845Option directives can be used to turn option flags on or off from
846within a DocTest case. The following example shows how a flag can be
847turned on and off. Note that comments on the same line as the option
848directive are ignored.
849
850 >>> def f(x): r'''
851 ... >>> print range(10) # Should fail: no ellipsis
852 ... [0, 1, ..., 9]
853 ...
854 ... >>> doctest: +ELLIPSIS # turn ellipsis on.
855 ... >>> print range(10) # Should succeed
856 ... [0, 1, ..., 9]
857 ...
858 ... >>> doctest: -ELLIPSIS # turn ellipsis back off.
859 ... >>> print range(10) # Should fail: no ellipsis
860 ... [0, 1, ..., 9]
861 ... '''
862 >>> test = doctest.DocTestFinder().find(f)[0]
863 >>> doctest.DocTestRunner(verbose=False).run(test)
864 **********************************************************************
865 Failure in example: print range(10) # Should fail: no ellipsis
866 from line #1 of f
867 Expected: [0, 1, ..., 9]
868 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
869 **********************************************************************
870 Failure in example: print range(10) # Should fail: no ellipsis
871 from line #9 of f
872 Expected: [0, 1, ..., 9]
873 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
874 (2, 3)
875
876Multiple flags can be toggled by a single option directive:
877
878 >>> def f(x): r'''
879 ... >>> print range(10) # Should fail
880 ... [0, 1, ..., 9]
881 ... >>> doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
882 ... >>> print range(10) # Should succeed
883 ... [0, 1, ..., 9]
884 ... '''
885 >>> test = doctest.DocTestFinder().find(f)[0]
886 >>> doctest.DocTestRunner(verbose=False).run(test)
887 **********************************************************************
888 Failure in example: print range(10) # Should fail
889 from line #1 of f
890 Expected: [0, 1, ..., 9]
891 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
892 (1, 2)
893"""
894
895def test_testsource(): r"""
896Unit tests for `testsource()`.
897
898The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +0000899test with that name in that module, and converts it to a script. The
900example code is converted to regular Python code. The surrounding
901words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +0000902
903 >>> import test.test_doctest
904 >>> name = 'test.test_doctest.sample_func'
905 >>> print doctest.testsource(test.test_doctest, name)
Tim Peters19397e52004-08-06 22:02:59 +0000906 # Blah blah
907 #
Tim Peters8485b562004-08-04 18:46:34 +0000908 print sample_func(22)
909 # Expected:
910 # 44
Tim Peters19397e52004-08-06 22:02:59 +0000911 #
912 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +0000913
914 >>> name = 'test.test_doctest.SampleNewStyleClass'
915 >>> print doctest.testsource(test.test_doctest, name)
916 print '1\n2\n3'
917 # Expected:
918 # 1
919 # 2
920 # 3
921
922 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
923 >>> print doctest.testsource(test.test_doctest, name)
924 print SampleClass.a_classmethod(10)
925 # Expected:
926 # 12
927 print SampleClass(0).a_classmethod(10)
928 # Expected:
929 # 12
930"""
931
932def test_debug(): r"""
933
934Create a docstring that we want to debug:
935
936 >>> s = '''
937 ... >>> x = 12
938 ... >>> print x
939 ... 12
940 ... '''
941
942Create some fake stdin input, to feed to the debugger:
943
944 >>> import tempfile
945 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
946 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
947 >>> fake_stdin.seek(0)
948 >>> real_stdin = sys.stdin
949 >>> sys.stdin = fake_stdin
950
951Run the debugger on the docstring, and then restore sys.stdin.
952
953 >>> doctest: +NORMALIZE_WHITESPACE
954 >>> try:
955 ... doctest.debug_src(s)
956 ... finally:
957 ... sys.stdin = real_stdin
958 ... fake_stdin.close()
959 > <string>(1)?()
960 (Pdb) 12
961 --Return--
962 > <string>(1)?()->None
963 (Pdb) 12
964 (Pdb)
965
966"""
967
Tim Peters19397e52004-08-06 22:02:59 +0000968def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +0000969 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +0000970
971 We create a Suite by providing a module. A module can be provided
972 by passing a module object:
973
974 >>> import unittest
975 >>> import test.sample_doctest
976 >>> suite = doctest.DocTestSuite(test.sample_doctest)
977 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +0000978 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +0000979
980 We can also supply the module by name:
981
982 >>> suite = doctest.DocTestSuite('test.sample_doctest')
983 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +0000984 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +0000985
986 We can use the current module:
987
988 >>> suite = test.sample_doctest.test_suite()
989 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +0000990 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +0000991
992 We can supply global variables. If we pass globs, they will be
993 used instead of the module globals. Here we'll pass an empty
994 globals, triggering an extra error:
995
996 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
997 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +0000998 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +0000999
1000 Alternatively, we can provide extra globals. Here we'll make an
1001 error go away by providing an extra global variable:
1002
1003 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1004 ... extraglobs={'y': 1})
1005 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001006 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001007
1008 You can pass option flags. Here we'll cause an extra error
1009 by disabling the blank-line feature:
1010
1011 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001012 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001013 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001014 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001015
Tim Peters1e277ee2004-08-07 05:37:52 +00001016 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001017
1018 >>> def setUp():
1019 ... import test.test_doctest
1020 ... test.test_doctest.sillySetup = True
1021
1022 >>> def tearDown():
1023 ... import test.test_doctest
1024 ... del test.test_doctest.sillySetup
1025
1026 Here, we installed a silly variable that the test expects:
1027
1028 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1029 ... setUp=setUp, tearDown=tearDown)
1030 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001031 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001032
1033 But the tearDown restores sanity:
1034
1035 >>> import test.test_doctest
1036 >>> test.test_doctest.sillySetup
1037 Traceback (most recent call last):
1038 ...
1039 AttributeError: 'module' object has no attribute 'sillySetup'
1040
1041 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001042 use a custom test_finder to to run just the test named bar.
1043 However, the test in the module docstring, and the two tests
1044 in the module __test__ dict, aren't filtered, so we actually
1045 run three tests besides bar's. The filtering mechanisms are
1046 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001047
1048 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001049 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001050 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1051 ... test_finder=finder)
1052 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001053 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001054 """
1055
1056def test_DocFileSuite():
1057 """We can test tests found in text files using a DocFileSuite.
1058
1059 We create a suite by providing the names of one or more text
1060 files that include examples:
1061
1062 >>> import unittest
1063 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1064 ... 'test_doctest2.txt')
1065 >>> suite.run(unittest.TestResult())
1066 <unittest.TestResult run=2 errors=0 failures=2>
1067
1068 The test files are looked for in the directory containing the
1069 calling module. A package keyword argument can be provided to
1070 specify a different relative location.
1071
1072 >>> import unittest
1073 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1074 ... 'test_doctest2.txt',
1075 ... package='test')
1076 >>> suite.run(unittest.TestResult())
1077 <unittest.TestResult run=2 errors=0 failures=2>
1078
1079 Note that '/' should be used as a path separator. It will be
1080 converted to a native separator at run time:
1081
1082
1083 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1084 >>> suite.run(unittest.TestResult())
1085 <unittest.TestResult run=1 errors=0 failures=1>
1086
1087 You can specify initial global variables:
1088
1089 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1090 ... 'test_doctest2.txt',
1091 ... globs={'favorite_color': 'blue'})
1092 >>> suite.run(unittest.TestResult())
1093 <unittest.TestResult run=2 errors=0 failures=1>
1094
1095 In this case, we supplied a missing favorite color. You can
1096 provide doctest options:
1097
1098 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1099 ... 'test_doctest2.txt',
1100 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1101 ... globs={'favorite_color': 'blue'})
1102 >>> suite.run(unittest.TestResult())
1103 <unittest.TestResult run=2 errors=0 failures=2>
1104
1105 And, you can provide setUp and tearDown functions:
1106
1107 You can supply setUp and teatDoen functions:
1108
1109 >>> def setUp():
1110 ... import test.test_doctest
1111 ... test.test_doctest.sillySetup = True
1112
1113 >>> def tearDown():
1114 ... import test.test_doctest
1115 ... del test.test_doctest.sillySetup
1116
1117 Here, we installed a silly variable that the test expects:
1118
1119 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1120 ... 'test_doctest2.txt',
1121 ... setUp=setUp, tearDown=tearDown)
1122 >>> suite.run(unittest.TestResult())
1123 <unittest.TestResult run=2 errors=0 failures=1>
1124
1125 But the tearDown restores sanity:
1126
1127 >>> import test.test_doctest
1128 >>> test.test_doctest.sillySetup
1129 Traceback (most recent call last):
1130 ...
1131 AttributeError: 'module' object has no attribute 'sillySetup'
1132
1133 """
1134
1135
Tim Peters8485b562004-08-04 18:46:34 +00001136######################################################################
1137## Main
1138######################################################################
1139
1140def test_main():
1141 # Check the doctest cases in doctest itself:
1142 test_support.run_doctest(doctest, verbosity=True)
1143 # Check the doctest cases defined here:
1144 from test import test_doctest
1145 test_support.run_doctest(test_doctest, verbosity=True)
1146
1147import trace, sys, re, StringIO
1148def test_coverage(coverdir):
1149 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1150 trace=0, count=1)
1151 tracer.run('reload(doctest); test_main()')
1152 r = tracer.results()
1153 print 'Writing coverage results...'
1154 r.write_results(show_missing=True, summary=True,
1155 coverdir=coverdir)
1156
1157if __name__ == '__main__':
1158 if '-c' in sys.argv:
1159 test_coverage('/tmp/doctest.cover')
1160 else:
1161 test_main()