blob: d9d0674d889aff23fefe9f719561afc5c54af1b6 [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):
Edward Loper7c748462004-08-09 02:06:06 +0000212 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: ' indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000213
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):
Edward Loper7c748462004-08-09 02:06:06 +0000232 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
233
234If there's no blank space after a PS2 prompt ('...'), then `DocTest`
235will raise a ValueError:
236
237 >>> docstring = '>>> if 1:\n...print 1\n1'
238 >>> doctest.DocTest(docstring, globs, 'some_test', 'filename', 0)
239 Traceback (most recent call last):
240 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
241
Tim Peters8485b562004-08-04 18:46:34 +0000242"""
243
244# [XX] test that it's getting line numbers right.
245def test_DocTestFinder(): r"""
246Unit tests for the `DocTestFinder` class.
247
248DocTestFinder is used to extract DocTests from an object's docstring
249and the docstrings of its contained objects. It can be used with
250modules, functions, classes, methods, staticmethods, classmethods, and
251properties.
252
253Finding Tests in Functions
254~~~~~~~~~~~~~~~~~~~~~~~~~~
255For a function whose docstring contains examples, DocTestFinder.find()
256will return a single test (for that function's docstring):
257
258 >>> # Allow ellipsis in the following examples (since the filename
259 >>> # and line number in the traceback can vary):
260 >>> doctest: +ELLIPSIS
261
262 >>> finder = doctest.DocTestFinder()
263 >>> tests = finder.find(sample_func)
264 >>> print tests
265 [<DocTest sample_func from ...:12 (1 example)>]
266 >>> e = tests[0].examples[0]
267 >>> print (e.source, e.want, e.lineno)
Tim Peters19397e52004-08-06 22:02:59 +0000268 ('print sample_func(22)', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000269
270 >>> doctest: -ELLIPSIS # Turn ellipsis back off
271
272If an object has no docstring, then a test is not created for it:
273
274 >>> def no_docstring(v):
275 ... pass
276 >>> finder.find(no_docstring)
277 []
278
279If the function has a docstring with no examples, then a test with no
280examples is returned. (This lets `DocTestRunner` collect statistics
281about which functions have no tests -- but is that useful? And should
282an empty test also be created when there's no docstring?)
283
284 >>> def no_examples(v):
285 ... ''' no doctest examples '''
286 >>> finder.find(no_examples)
287 [<DocTest no_examples from None:1 (no examples)>]
288
289Finding Tests in Classes
290~~~~~~~~~~~~~~~~~~~~~~~~
291For a class, DocTestFinder will create a test for the class's
292docstring, and will recursively explore its contents, including
293methods, classmethods, staticmethods, properties, and nested classes.
294
295 >>> finder = doctest.DocTestFinder()
296 >>> tests = finder.find(SampleClass)
297 >>> tests.sort()
298 >>> for t in tests:
299 ... print '%2s %s' % (len(t.examples), t.name)
300 1 SampleClass
301 3 SampleClass.NestedClass
302 1 SampleClass.NestedClass.__init__
303 1 SampleClass.__init__
304 2 SampleClass.a_classmethod
305 1 SampleClass.a_property
306 1 SampleClass.a_staticmethod
307 1 SampleClass.double
308 1 SampleClass.get
309
310New-style classes are also supported:
311
312 >>> tests = finder.find(SampleNewStyleClass)
313 >>> tests.sort()
314 >>> for t in tests:
315 ... print '%2s %s' % (len(t.examples), t.name)
316 1 SampleNewStyleClass
317 1 SampleNewStyleClass.__init__
318 1 SampleNewStyleClass.double
319 1 SampleNewStyleClass.get
320
321Finding Tests in Modules
322~~~~~~~~~~~~~~~~~~~~~~~~
323For a module, DocTestFinder will create a test for the class's
324docstring, and will recursively explore its contents, including
325functions, classes, and the `__test__` dictionary, if it exists:
326
327 >>> # A module
328 >>> import new
329 >>> m = new.module('some_module')
330 >>> def triple(val):
331 ... '''
332 ... >>> print tripple(11)
333 ... 33
334 ... '''
335 ... return val*3
336 >>> m.__dict__.update({
337 ... 'sample_func': sample_func,
338 ... 'SampleClass': SampleClass,
339 ... '__doc__': '''
340 ... Module docstring.
341 ... >>> print 'module'
342 ... module
343 ... ''',
344 ... '__test__': {
345 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
346 ... 'c': triple}})
347
348 >>> finder = doctest.DocTestFinder()
349 >>> # Use module=test.test_doctest, to prevent doctest from
350 >>> # ignoring the objects since they weren't defined in m.
351 >>> import test.test_doctest
352 >>> tests = finder.find(m, module=test.test_doctest)
353 >>> tests.sort()
354 >>> for t in tests:
355 ... print '%2s %s' % (len(t.examples), t.name)
356 1 some_module
357 1 some_module.SampleClass
358 3 some_module.SampleClass.NestedClass
359 1 some_module.SampleClass.NestedClass.__init__
360 1 some_module.SampleClass.__init__
361 2 some_module.SampleClass.a_classmethod
362 1 some_module.SampleClass.a_property
363 1 some_module.SampleClass.a_staticmethod
364 1 some_module.SampleClass.double
365 1 some_module.SampleClass.get
366 1 some_module.c
367 2 some_module.d
368 1 some_module.sample_func
369
370Duplicate Removal
371~~~~~~~~~~~~~~~~~
372If a single object is listed twice (under different names), then tests
373will only be generated for it once:
374
Tim Petersf3f57472004-08-08 06:11:48 +0000375 >>> from test import doctest_aliases
376 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000377 >>> tests.sort()
378 >>> print len(tests)
379 2
380 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000381 test.doctest_aliases.TwoNames
382
383 TwoNames.f and TwoNames.g are bound to the same object.
384 We can't guess which will be found in doctest's traversal of
385 TwoNames.__dict__ first, so we have to allow for either.
386
387 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000388 True
389
390Filter Functions
391~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000392A filter function can be used to restrict which objects get examined,
393but this is temporary, undocumented internal support for testmod's
394deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000395
396 >>> def namefilter(prefix, base):
397 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000398 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000399 >>> tests.sort()
400 >>> for t in tests:
401 ... print '%2s %s' % (len(t.examples), t.name)
402 1 SampleClass
403 3 SampleClass.NestedClass
404 1 SampleClass.NestedClass.__init__
405 1 SampleClass.__init__
406 1 SampleClass.double
407 1 SampleClass.get
408
Tim Peters8485b562004-08-04 18:46:34 +0000409If a given object is filtered out, then none of the objects that it
410contains will be added either:
411
412 >>> def namefilter(prefix, base):
413 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000414 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000415 >>> tests.sort()
416 >>> for t in tests:
417 ... print '%2s %s' % (len(t.examples), t.name)
418 1 SampleClass
419 1 SampleClass.__init__
420 2 SampleClass.a_classmethod
421 1 SampleClass.a_property
422 1 SampleClass.a_staticmethod
423 1 SampleClass.double
424 1 SampleClass.get
425
Tim Petersf727c6c2004-08-08 01:48:59 +0000426The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000427object explicitly passed to DocTestFinder:
428
429 >>> def namefilter(prefix, base):
430 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000431 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000432 >>> len(tests)
433 9
434
435Turning off Recursion
436~~~~~~~~~~~~~~~~~~~~~
437DocTestFinder can be told not to look for tests in contained objects
438using the `recurse` flag:
439
440 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
441 >>> tests.sort()
442 >>> for t in tests:
443 ... print '%2s %s' % (len(t.examples), t.name)
444 1 SampleClass
445"""
446
447class test_DocTestRunner:
448 def basics(): r"""
449Unit tests for the `DocTestRunner` class.
450
451DocTestRunner is used to run DocTest test cases, and to accumulate
452statistics. Here's a simple DocTest case we can use:
453
454 >>> def f(x):
455 ... '''
456 ... >>> x = 12
457 ... >>> print x
458 ... 12
459 ... >>> x/2
460 ... 6
461 ... '''
462 >>> test = doctest.DocTestFinder().find(f)[0]
463
464The main DocTestRunner interface is the `run` method, which runs a
465given DocTest case in a given namespace (globs). It returns a tuple
466`(f,t)`, where `f` is the number of failed tests and `t` is the number
467of tried tests.
468
469 >>> doctest.DocTestRunner(verbose=False).run(test)
470 (0, 3)
471
472If any example produces incorrect output, then the test runner reports
473the failure and proceeds to the next example:
474
475 >>> def f(x):
476 ... '''
477 ... >>> x = 12
478 ... >>> print x
479 ... 14
480 ... >>> x/2
481 ... 6
482 ... '''
483 >>> test = doctest.DocTestFinder().find(f)[0]
484 >>> doctest.DocTestRunner(verbose=True).run(test)
485 Trying: x = 12
486 Expecting: nothing
487 ok
488 Trying: print x
489 Expecting: 14
490 **********************************************************************
491 Failure in example: print x
492 from line #2 of f
493 Expected: 14
494 Got: 12
495 Trying: x/2
496 Expecting: 6
497 ok
498 (1, 3)
499"""
500 def verbose_flag(): r"""
501The `verbose` flag makes the test runner generate more detailed
502output:
503
504 >>> def f(x):
505 ... '''
506 ... >>> x = 12
507 ... >>> print x
508 ... 12
509 ... >>> x/2
510 ... 6
511 ... '''
512 >>> test = doctest.DocTestFinder().find(f)[0]
513
514 >>> doctest.DocTestRunner(verbose=True).run(test)
515 Trying: x = 12
516 Expecting: nothing
517 ok
518 Trying: print x
519 Expecting: 12
520 ok
521 Trying: x/2
522 Expecting: 6
523 ok
524 (0, 3)
525
526If the `verbose` flag is unspecified, then the output will be verbose
527iff `-v` appears in sys.argv:
528
529 >>> # Save the real sys.argv list.
530 >>> old_argv = sys.argv
531
532 >>> # If -v does not appear in sys.argv, then output isn't verbose.
533 >>> sys.argv = ['test']
534 >>> doctest.DocTestRunner().run(test)
535 (0, 3)
536
537 >>> # If -v does appear in sys.argv, then output is verbose.
538 >>> sys.argv = ['test', '-v']
539 >>> doctest.DocTestRunner().run(test)
540 Trying: x = 12
541 Expecting: nothing
542 ok
543 Trying: print x
544 Expecting: 12
545 ok
546 Trying: x/2
547 Expecting: 6
548 ok
549 (0, 3)
550
551 >>> # Restore sys.argv
552 >>> sys.argv = old_argv
553
554In the remaining examples, the test runner's verbosity will be
555explicitly set, to ensure that the test behavior is consistent.
556 """
557 def exceptions(): r"""
558Tests of `DocTestRunner`'s exception handling.
559
560An expected exception is specified with a traceback message. The
561lines between the first line and the type/value may be omitted or
562replaced with any other string:
563
564 >>> def f(x):
565 ... '''
566 ... >>> x = 12
567 ... >>> print x/0
568 ... Traceback (most recent call last):
569 ... ZeroDivisionError: integer division or modulo by zero
570 ... '''
571 >>> test = doctest.DocTestFinder().find(f)[0]
572 >>> doctest.DocTestRunner(verbose=False).run(test)
573 (0, 2)
574
575An example may generate output before it raises an exception; if it
576does, then the output must match the expected output:
577
578 >>> def f(x):
579 ... '''
580 ... >>> x = 12
581 ... >>> print 'pre-exception output', x/0
582 ... pre-exception output
583 ... Traceback (most recent call last):
584 ... ZeroDivisionError: integer division or modulo by zero
585 ... '''
586 >>> test = doctest.DocTestFinder().find(f)[0]
587 >>> doctest.DocTestRunner(verbose=False).run(test)
588 (0, 2)
589
590Exception messages may contain newlines:
591
592 >>> def f(x):
593 ... r'''
594 ... >>> raise ValueError, 'multi\nline\nmessage'
595 ... Traceback (most recent call last):
596 ... ValueError: multi
597 ... line
598 ... message
599 ... '''
600 >>> test = doctest.DocTestFinder().find(f)[0]
601 >>> doctest.DocTestRunner(verbose=False).run(test)
602 (0, 1)
603
604If an exception is expected, but an exception with the wrong type or
605message is raised, then it is reported as a failure:
606
607 >>> def f(x):
608 ... r'''
609 ... >>> raise ValueError, 'message'
610 ... Traceback (most recent call last):
611 ... ValueError: wrong message
612 ... '''
613 >>> test = doctest.DocTestFinder().find(f)[0]
614 >>> doctest.DocTestRunner(verbose=False).run(test)
615 **********************************************************************
616 Failure in example: raise ValueError, 'message'
617 from line #1 of f
618 Expected:
619 Traceback (most recent call last):
620 ValueError: wrong message
621 Got:
622 Traceback (most recent call last):
623 ValueError: message
624 (1, 1)
625
626If an exception is raised but not expected, then it is reported as an
627unexpected exception:
628
629 >>> # Allow ellipsis in the following examples (since the filename
630 >>> # and line number in the traceback can vary):
631 >>> doctest: +ELLIPSIS
632
633 >>> def f(x):
634 ... r'''
635 ... >>> 1/0
636 ... 0
637 ... '''
638 >>> test = doctest.DocTestFinder().find(f)[0]
639 >>> doctest.DocTestRunner(verbose=False).run(test)
640 **********************************************************************
641 Failure in example: 1/0
642 from line #1 of f
643 Exception raised:
644 Traceback (most recent call last):
645 ...
646 ZeroDivisionError: integer division or modulo by zero
647 (1, 1)
648
649 >>> doctest: -ELLIPSIS # Turn ellipsis back off:
650"""
651 def optionflags(): r"""
652Tests of `DocTestRunner`'s option flag handling.
653
654Several option flags can be used to customize the behavior of the test
655runner. These are defined as module constants in doctest, and passed
656to the DocTestRunner constructor (multiple constants should be or-ed
657together).
658
659The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
660and 1/0:
661
662 >>> def f(x):
663 ... '>>> True\n1\n'
664
665 >>> # Without the flag:
666 >>> test = doctest.DocTestFinder().find(f)[0]
667 >>> doctest.DocTestRunner(verbose=False).run(test)
668 (0, 1)
669
670 >>> # With the flag:
671 >>> test = doctest.DocTestFinder().find(f)[0]
672 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
673 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
674 **********************************************************************
675 Failure in example: True
676 from line #0 of f
677 Expected: 1
678 Got: True
679 (1, 1)
680
681The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
682and the '<BLANKLINE>' marker:
683
684 >>> def f(x):
685 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
686
687 >>> # Without the flag:
688 >>> test = doctest.DocTestFinder().find(f)[0]
689 >>> doctest.DocTestRunner(verbose=False).run(test)
690 (0, 1)
691
692 >>> # With the flag:
693 >>> test = doctest.DocTestFinder().find(f)[0]
694 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
695 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
696 **********************************************************************
697 Failure in example: print "a\n\nb"
698 from line #0 of f
699 Expected:
700 a
701 <BLANKLINE>
702 b
703 Got:
704 a
705 <BLANKLINE>
706 b
707 (1, 1)
708
709The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
710treated as equal:
711
712 >>> def f(x):
713 ... '>>> print 1, 2, 3\n 1 2\n 3'
714
715 >>> # Without the flag:
716 >>> test = doctest.DocTestFinder().find(f)[0]
717 >>> doctest.DocTestRunner(verbose=False).run(test)
718 **********************************************************************
719 Failure in example: print 1, 2, 3
720 from line #0 of f
721 Expected:
722 1 2
723 3
724 Got: 1 2 3
725 (1, 1)
726
727 >>> # With the flag:
728 >>> test = doctest.DocTestFinder().find(f)[0]
729 >>> flags = doctest.NORMALIZE_WHITESPACE
730 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
731 (0, 1)
732
733The ELLIPSIS flag causes ellipsis marker ("...") in the expected
734output to match any substring in the actual output:
735
736 >>> def f(x):
737 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
738
739 >>> # Without the flag:
740 >>> test = doctest.DocTestFinder().find(f)[0]
741 >>> doctest.DocTestRunner(verbose=False).run(test)
742 **********************************************************************
743 Failure in example: print range(15)
744 from line #0 of f
745 Expected: [0, 1, 2, ..., 14]
746 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
747 (1, 1)
748
749 >>> # With the flag:
750 >>> test = doctest.DocTestFinder().find(f)[0]
751 >>> flags = doctest.ELLIPSIS
752 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
753 (0, 1)
754
755The UNIFIED_DIFF flag causes failures that involve multi-line expected
756and actual outputs to be displayed using a unified diff:
757
758 >>> def f(x):
759 ... r'''
760 ... >>> print '\n'.join('abcdefg')
761 ... a
762 ... B
763 ... c
764 ... d
765 ... f
766 ... g
767 ... h
768 ... '''
769
770 >>> # Without the flag:
771 >>> test = doctest.DocTestFinder().find(f)[0]
772 >>> doctest.DocTestRunner(verbose=False).run(test)
773 **********************************************************************
774 Failure in example: print '\n'.join('abcdefg')
775 from line #1 of f
776 Expected:
777 a
778 B
779 c
780 d
781 f
782 g
783 h
784 Got:
785 a
786 b
787 c
788 d
789 e
790 f
791 g
792 (1, 1)
793
794 >>> # With the flag:
795 >>> test = doctest.DocTestFinder().find(f)[0]
796 >>> flags = doctest.UNIFIED_DIFF
797 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
798 **********************************************************************
799 Failure in example: print '\n'.join('abcdefg')
800 from line #1 of f
801 Differences (unified diff):
802 --- Expected
803 +++ Got
804 @@ -1,8 +1,8 @@
805 a
806 -B
807 +b
808 c
809 d
810 +e
811 f
812 g
813 -h
814 <BLANKLINE>
815 (1, 1)
816
817The CONTEXT_DIFF flag causes failures that involve multi-line expected
818and actual outputs to be displayed using a context diff:
819
820 >>> # Reuse f() from the UNIFIED_DIFF example, above.
821 >>> test = doctest.DocTestFinder().find(f)[0]
822 >>> flags = doctest.CONTEXT_DIFF
823 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
824 **********************************************************************
825 Failure in example: print '\n'.join('abcdefg')
826 from line #1 of f
827 Differences (context diff):
828 *** Expected
829 --- Got
830 ***************
831 *** 1,8 ****
832 a
833 ! B
834 c
835 d
836 f
837 g
838 - h
839 <BLANKLINE>
840 --- 1,8 ----
841 a
842 ! b
843 c
844 d
845 + e
846 f
847 g
848 <BLANKLINE>
849 (1, 1)
850"""
851 def option_directives(): r"""
852Tests of `DocTestRunner`'s option directive mechanism.
853
854Option directives can be used to turn option flags on or off from
855within a DocTest case. The following example shows how a flag can be
856turned on and off. Note that comments on the same line as the option
857directive are ignored.
858
859 >>> def f(x): r'''
860 ... >>> print range(10) # Should fail: no ellipsis
861 ... [0, 1, ..., 9]
862 ...
863 ... >>> doctest: +ELLIPSIS # turn ellipsis on.
864 ... >>> print range(10) # Should succeed
865 ... [0, 1, ..., 9]
866 ...
867 ... >>> doctest: -ELLIPSIS # turn ellipsis back off.
868 ... >>> print range(10) # Should fail: no ellipsis
869 ... [0, 1, ..., 9]
870 ... '''
871 >>> test = doctest.DocTestFinder().find(f)[0]
872 >>> doctest.DocTestRunner(verbose=False).run(test)
873 **********************************************************************
874 Failure in example: print range(10) # Should fail: no ellipsis
875 from line #1 of f
876 Expected: [0, 1, ..., 9]
877 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
878 **********************************************************************
879 Failure in example: print range(10) # Should fail: no ellipsis
880 from line #9 of f
881 Expected: [0, 1, ..., 9]
882 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
883 (2, 3)
884
885Multiple flags can be toggled by a single option directive:
886
887 >>> def f(x): r'''
888 ... >>> print range(10) # Should fail
889 ... [0, 1, ..., 9]
890 ... >>> doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
891 ... >>> print range(10) # Should succeed
892 ... [0, 1, ..., 9]
893 ... '''
894 >>> test = doctest.DocTestFinder().find(f)[0]
895 >>> doctest.DocTestRunner(verbose=False).run(test)
896 **********************************************************************
897 Failure in example: print range(10) # Should fail
898 from line #1 of f
899 Expected: [0, 1, ..., 9]
900 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
901 (1, 2)
902"""
903
904def test_testsource(): r"""
905Unit tests for `testsource()`.
906
907The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +0000908test with that name in that module, and converts it to a script. The
909example code is converted to regular Python code. The surrounding
910words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +0000911
912 >>> import test.test_doctest
913 >>> name = 'test.test_doctest.sample_func'
914 >>> print doctest.testsource(test.test_doctest, name)
Tim Peters19397e52004-08-06 22:02:59 +0000915 # Blah blah
916 #
Tim Peters8485b562004-08-04 18:46:34 +0000917 print sample_func(22)
918 # Expected:
919 # 44
Tim Peters19397e52004-08-06 22:02:59 +0000920 #
921 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +0000922
923 >>> name = 'test.test_doctest.SampleNewStyleClass'
924 >>> print doctest.testsource(test.test_doctest, name)
925 print '1\n2\n3'
926 # Expected:
927 # 1
928 # 2
929 # 3
930
931 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
932 >>> print doctest.testsource(test.test_doctest, name)
933 print SampleClass.a_classmethod(10)
934 # Expected:
935 # 12
936 print SampleClass(0).a_classmethod(10)
937 # Expected:
938 # 12
939"""
940
941def test_debug(): r"""
942
943Create a docstring that we want to debug:
944
945 >>> s = '''
946 ... >>> x = 12
947 ... >>> print x
948 ... 12
949 ... '''
950
951Create some fake stdin input, to feed to the debugger:
952
953 >>> import tempfile
954 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
955 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
956 >>> fake_stdin.seek(0)
957 >>> real_stdin = sys.stdin
958 >>> sys.stdin = fake_stdin
959
960Run the debugger on the docstring, and then restore sys.stdin.
961
962 >>> doctest: +NORMALIZE_WHITESPACE
963 >>> try:
964 ... doctest.debug_src(s)
965 ... finally:
966 ... sys.stdin = real_stdin
967 ... fake_stdin.close()
968 > <string>(1)?()
969 (Pdb) 12
970 --Return--
971 > <string>(1)?()->None
972 (Pdb) 12
973 (Pdb)
974
975"""
976
Tim Peters19397e52004-08-06 22:02:59 +0000977def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +0000978 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +0000979
980 We create a Suite by providing a module. A module can be provided
981 by passing a module object:
982
983 >>> import unittest
984 >>> import test.sample_doctest
985 >>> suite = doctest.DocTestSuite(test.sample_doctest)
986 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +0000987 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +0000988
989 We can also supply the module by name:
990
991 >>> suite = doctest.DocTestSuite('test.sample_doctest')
992 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +0000993 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +0000994
995 We can use the current module:
996
997 >>> suite = test.sample_doctest.test_suite()
998 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +0000999 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001000
1001 We can supply global variables. If we pass globs, they will be
1002 used instead of the module globals. Here we'll pass an empty
1003 globals, triggering an extra error:
1004
1005 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1006 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001007 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001008
1009 Alternatively, we can provide extra globals. Here we'll make an
1010 error go away by providing an extra global variable:
1011
1012 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1013 ... extraglobs={'y': 1})
1014 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001015 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001016
1017 You can pass option flags. Here we'll cause an extra error
1018 by disabling the blank-line feature:
1019
1020 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001021 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001022 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001023 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001024
Tim Peters1e277ee2004-08-07 05:37:52 +00001025 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001026
1027 >>> def setUp():
1028 ... import test.test_doctest
1029 ... test.test_doctest.sillySetup = True
1030
1031 >>> def tearDown():
1032 ... import test.test_doctest
1033 ... del test.test_doctest.sillySetup
1034
1035 Here, we installed a silly variable that the test expects:
1036
1037 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1038 ... setUp=setUp, tearDown=tearDown)
1039 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001040 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001041
1042 But the tearDown restores sanity:
1043
1044 >>> import test.test_doctest
1045 >>> test.test_doctest.sillySetup
1046 Traceback (most recent call last):
1047 ...
1048 AttributeError: 'module' object has no attribute 'sillySetup'
1049
1050 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001051 use a custom test_finder to to run just the test named bar.
1052 However, the test in the module docstring, and the two tests
1053 in the module __test__ dict, aren't filtered, so we actually
1054 run three tests besides bar's. The filtering mechanisms are
1055 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001056
1057 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001058 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001059 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1060 ... test_finder=finder)
1061 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001062 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001063 """
1064
1065def test_DocFileSuite():
1066 """We can test tests found in text files using a DocFileSuite.
1067
1068 We create a suite by providing the names of one or more text
1069 files that include examples:
1070
1071 >>> import unittest
1072 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1073 ... 'test_doctest2.txt')
1074 >>> suite.run(unittest.TestResult())
1075 <unittest.TestResult run=2 errors=0 failures=2>
1076
1077 The test files are looked for in the directory containing the
1078 calling module. A package keyword argument can be provided to
1079 specify a different relative location.
1080
1081 >>> import unittest
1082 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1083 ... 'test_doctest2.txt',
1084 ... package='test')
1085 >>> suite.run(unittest.TestResult())
1086 <unittest.TestResult run=2 errors=0 failures=2>
1087
1088 Note that '/' should be used as a path separator. It will be
1089 converted to a native separator at run time:
1090
1091
1092 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1093 >>> suite.run(unittest.TestResult())
1094 <unittest.TestResult run=1 errors=0 failures=1>
1095
1096 You can specify initial global variables:
1097
1098 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1099 ... 'test_doctest2.txt',
1100 ... globs={'favorite_color': 'blue'})
1101 >>> suite.run(unittest.TestResult())
1102 <unittest.TestResult run=2 errors=0 failures=1>
1103
1104 In this case, we supplied a missing favorite color. You can
1105 provide doctest options:
1106
1107 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1108 ... 'test_doctest2.txt',
1109 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1110 ... globs={'favorite_color': 'blue'})
1111 >>> suite.run(unittest.TestResult())
1112 <unittest.TestResult run=2 errors=0 failures=2>
1113
1114 And, you can provide setUp and tearDown functions:
1115
1116 You can supply setUp and teatDoen functions:
1117
1118 >>> def setUp():
1119 ... import test.test_doctest
1120 ... test.test_doctest.sillySetup = True
1121
1122 >>> def tearDown():
1123 ... import test.test_doctest
1124 ... del test.test_doctest.sillySetup
1125
1126 Here, we installed a silly variable that the test expects:
1127
1128 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1129 ... 'test_doctest2.txt',
1130 ... setUp=setUp, tearDown=tearDown)
1131 >>> suite.run(unittest.TestResult())
1132 <unittest.TestResult run=2 errors=0 failures=1>
1133
1134 But the tearDown restores sanity:
1135
1136 >>> import test.test_doctest
1137 >>> test.test_doctest.sillySetup
1138 Traceback (most recent call last):
1139 ...
1140 AttributeError: 'module' object has no attribute 'sillySetup'
1141
1142 """
1143
1144
Tim Peters8485b562004-08-04 18:46:34 +00001145######################################################################
1146## Main
1147######################################################################
1148
1149def test_main():
1150 # Check the doctest cases in doctest itself:
1151 test_support.run_doctest(doctest, verbosity=True)
1152 # Check the doctest cases defined here:
1153 from test import test_doctest
1154 test_support.run_doctest(test_doctest, verbosity=True)
1155
1156import trace, sys, re, StringIO
1157def test_coverage(coverdir):
1158 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1159 trace=0, count=1)
1160 tracer.run('reload(doctest); test_main()')
1161 r = tracer.results()
1162 print 'Writing coverage results...'
1163 r.write_results(show_missing=True, summary=True,
1164 coverdir=coverdir)
1165
1166if __name__ == '__main__':
1167 if '-c' in sys.argv:
1168 test_coverage('/tmp/doctest.cover')
1169 else:
1170 test_main()