blob: 50da872bc3dde102697258d2b2179ee7d4f10713 [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)
Tim Petersbb431472004-08-09 03:51:46 +0000130 ('print 1\n', '1\n', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000131
Tim Petersbb431472004-08-09 03:51:46 +0000132The `source` string ends in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000133
Tim Petersbb431472004-08-09 03:51:46 +0000134 Source spans a single line: no terminating newline.
Tim Peters8485b562004-08-04 18:46:34 +0000135 >>> e = doctest.Example('print 1', '1\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000136 >>> e.source, e.want
137 ('print 1\n', '1\n')
138
Tim Peters8485b562004-08-04 18:46:34 +0000139 >>> e = doctest.Example('print 1\n', '1\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000140 >>> e.source, e.want
141 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000142
Tim Petersbb431472004-08-09 03:51:46 +0000143 Source spans multiple lines: require terminating newline.
Tim Peters8485b562004-08-04 18:46:34 +0000144 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000145 >>> e.source, e.want
146 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000147
Tim Petersbb431472004-08-09 03:51:46 +0000148 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n', 0)
149 >>> e.source, e.want
150 ('print 1;\nprint 2\n', '1\n2\n')
151
152The `want` string ends with a newline, unless it's the empty string:
Tim Peters8485b562004-08-04 18:46:34 +0000153
154 >>> e = doctest.Example('print 1', '1\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000155 >>> e.source, e.want
156 ('print 1\n', '1\n')
157
Tim Peters8485b562004-08-04 18:46:34 +0000158 >>> e = doctest.Example('print 1', '1', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000159 >>> e.source, e.want
160 ('print 1\n', '1\n')
161
Tim Peters8485b562004-08-04 18:46:34 +0000162 >>> e = doctest.Example('print', '', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000163 >>> e.source, e.want
164 ('print\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000165"""
166
167def test_DocTest(): r"""
168Unit tests for the `DocTest` class.
169
170DocTest is a collection of examples, extracted from a docstring, along
171with information about where the docstring comes from (a name,
172filename, and line number). The docstring is parsed by the `DocTest`
173constructor:
174
175 >>> docstring = '''
176 ... >>> print 12
177 ... 12
178 ...
179 ... Non-example text.
180 ...
181 ... >>> print 'another\example'
182 ... another
183 ... example
184 ... '''
185 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000186 >>> parser = doctest.DocTestParser()
187 >>> test = parser.get_doctest(docstring, globs, 'some_test',
188 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000189 >>> print test
190 <DocTest some_test from some_file:20 (2 examples)>
191 >>> len(test.examples)
192 2
193 >>> e1, e2 = test.examples
194 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000195 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000196 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000197 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000198
199Source information (name, filename, and line number) is available as
200attributes on the doctest object:
201
202 >>> (test.name, test.filename, test.lineno)
203 ('some_test', 'some_file', 20)
204
205The line number of an example within its containing file is found by
206adding the line number of the example and the line number of its
207containing test:
208
209 >>> test.lineno + e1.lineno
210 21
211 >>> test.lineno + e2.lineno
212 26
213
214If the docstring contains inconsistant leading whitespace in the
215expected output of an example, then `DocTest` will raise a ValueError:
216
217 >>> docstring = r'''
218 ... >>> print 'bad\nindentation'
219 ... bad
220 ... indentation
221 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000222 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000223 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000224 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: ' indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000225
226If the docstring contains inconsistent leading whitespace on
227continuation lines, then `DocTest` will raise a ValueError:
228
229 >>> docstring = r'''
230 ... >>> print ('bad indentation',
231 ... ... 2)
232 ... ('bad', 'indentation')
233 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000234 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000235 Traceback (most recent call last):
236 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: ' ... 2)'
237
238If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
239will raise a ValueError:
240
241 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000242 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000243 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000244 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
245
246If there's no blank space after a PS2 prompt ('...'), then `DocTest`
247will raise a ValueError:
248
249 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000250 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000251 Traceback (most recent call last):
252 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
253
Tim Peters8485b562004-08-04 18:46:34 +0000254"""
255
256# [XX] test that it's getting line numbers right.
257def 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
270 >>> # Allow ellipsis in the following examples (since the filename
271 >>> # and line number in the traceback can vary):
272 >>> doctest: +ELLIPSIS
273
274 >>> finder = doctest.DocTestFinder()
275 >>> tests = finder.find(sample_func)
276 >>> print tests
277 [<DocTest sample_func from ...:12 (1 example)>]
278 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000279 >>> (e.source, e.want, e.lineno)
280 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000281
282 >>> doctest: -ELLIPSIS # Turn ellipsis back off
283
284If an object has no docstring, then a test is not created for it:
285
286 >>> def no_docstring(v):
287 ... pass
288 >>> finder.find(no_docstring)
289 []
290
291If the function has a docstring with no examples, then a test with no
292examples is returned. (This lets `DocTestRunner` collect statistics
293about which functions have no tests -- but is that useful? And should
294an empty test also be created when there's no docstring?)
295
296 >>> def no_examples(v):
297 ... ''' no doctest examples '''
298 >>> finder.find(no_examples)
299 [<DocTest no_examples from None:1 (no examples)>]
300
301Finding Tests in Classes
302~~~~~~~~~~~~~~~~~~~~~~~~
303For a class, DocTestFinder will create a test for the class's
304docstring, and will recursively explore its contents, including
305methods, classmethods, staticmethods, properties, and nested classes.
306
307 >>> finder = doctest.DocTestFinder()
308 >>> tests = finder.find(SampleClass)
309 >>> tests.sort()
310 >>> for t in tests:
311 ... print '%2s %s' % (len(t.examples), t.name)
312 1 SampleClass
313 3 SampleClass.NestedClass
314 1 SampleClass.NestedClass.__init__
315 1 SampleClass.__init__
316 2 SampleClass.a_classmethod
317 1 SampleClass.a_property
318 1 SampleClass.a_staticmethod
319 1 SampleClass.double
320 1 SampleClass.get
321
322New-style classes are also supported:
323
324 >>> tests = finder.find(SampleNewStyleClass)
325 >>> tests.sort()
326 >>> for t in tests:
327 ... print '%2s %s' % (len(t.examples), t.name)
328 1 SampleNewStyleClass
329 1 SampleNewStyleClass.__init__
330 1 SampleNewStyleClass.double
331 1 SampleNewStyleClass.get
332
333Finding Tests in Modules
334~~~~~~~~~~~~~~~~~~~~~~~~
335For a module, DocTestFinder will create a test for the class's
336docstring, and will recursively explore its contents, including
337functions, classes, and the `__test__` dictionary, if it exists:
338
339 >>> # A module
340 >>> import new
341 >>> m = new.module('some_module')
342 >>> def triple(val):
343 ... '''
344 ... >>> print tripple(11)
345 ... 33
346 ... '''
347 ... return val*3
348 >>> m.__dict__.update({
349 ... 'sample_func': sample_func,
350 ... 'SampleClass': SampleClass,
351 ... '__doc__': '''
352 ... Module docstring.
353 ... >>> print 'module'
354 ... module
355 ... ''',
356 ... '__test__': {
357 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
358 ... 'c': triple}})
359
360 >>> finder = doctest.DocTestFinder()
361 >>> # Use module=test.test_doctest, to prevent doctest from
362 >>> # ignoring the objects since they weren't defined in m.
363 >>> import test.test_doctest
364 >>> tests = finder.find(m, module=test.test_doctest)
365 >>> tests.sort()
366 >>> for t in tests:
367 ... print '%2s %s' % (len(t.examples), t.name)
368 1 some_module
369 1 some_module.SampleClass
370 3 some_module.SampleClass.NestedClass
371 1 some_module.SampleClass.NestedClass.__init__
372 1 some_module.SampleClass.__init__
373 2 some_module.SampleClass.a_classmethod
374 1 some_module.SampleClass.a_property
375 1 some_module.SampleClass.a_staticmethod
376 1 some_module.SampleClass.double
377 1 some_module.SampleClass.get
378 1 some_module.c
379 2 some_module.d
380 1 some_module.sample_func
381
382Duplicate Removal
383~~~~~~~~~~~~~~~~~
384If a single object is listed twice (under different names), then tests
385will only be generated for it once:
386
Tim Petersf3f57472004-08-08 06:11:48 +0000387 >>> from test import doctest_aliases
388 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000389 >>> tests.sort()
390 >>> print len(tests)
391 2
392 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000393 test.doctest_aliases.TwoNames
394
395 TwoNames.f and TwoNames.g are bound to the same object.
396 We can't guess which will be found in doctest's traversal of
397 TwoNames.__dict__ first, so we have to allow for either.
398
399 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000400 True
401
402Filter Functions
403~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000404A filter function can be used to restrict which objects get examined,
405but this is temporary, undocumented internal support for testmod's
406deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000407
408 >>> def namefilter(prefix, base):
409 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000410 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000411 >>> tests.sort()
412 >>> for t in tests:
413 ... print '%2s %s' % (len(t.examples), t.name)
414 1 SampleClass
415 3 SampleClass.NestedClass
416 1 SampleClass.NestedClass.__init__
417 1 SampleClass.__init__
418 1 SampleClass.double
419 1 SampleClass.get
420
Tim Peters8485b562004-08-04 18:46:34 +0000421If a given object is filtered out, then none of the objects that it
422contains will be added either:
423
424 >>> def namefilter(prefix, base):
425 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000426 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000427 >>> tests.sort()
428 >>> for t in tests:
429 ... print '%2s %s' % (len(t.examples), t.name)
430 1 SampleClass
431 1 SampleClass.__init__
432 2 SampleClass.a_classmethod
433 1 SampleClass.a_property
434 1 SampleClass.a_staticmethod
435 1 SampleClass.double
436 1 SampleClass.get
437
Tim Petersf727c6c2004-08-08 01:48:59 +0000438The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000439object explicitly passed to DocTestFinder:
440
441 >>> def namefilter(prefix, base):
442 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000443 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000444 >>> len(tests)
445 9
446
447Turning off Recursion
448~~~~~~~~~~~~~~~~~~~~~
449DocTestFinder can be told not to look for tests in contained objects
450using the `recurse` flag:
451
452 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
453 >>> tests.sort()
454 >>> for t in tests:
455 ... print '%2s %s' % (len(t.examples), t.name)
456 1 SampleClass
457"""
458
459class test_DocTestRunner:
460 def basics(): r"""
461Unit tests for the `DocTestRunner` class.
462
463DocTestRunner is used to run DocTest test cases, and to accumulate
464statistics. Here's a simple DocTest case we can use:
465
466 >>> def f(x):
467 ... '''
468 ... >>> x = 12
469 ... >>> print x
470 ... 12
471 ... >>> x/2
472 ... 6
473 ... '''
474 >>> test = doctest.DocTestFinder().find(f)[0]
475
476The main DocTestRunner interface is the `run` method, which runs a
477given DocTest case in a given namespace (globs). It returns a tuple
478`(f,t)`, where `f` is the number of failed tests and `t` is the number
479of tried tests.
480
481 >>> doctest.DocTestRunner(verbose=False).run(test)
482 (0, 3)
483
484If any example produces incorrect output, then the test runner reports
485the failure and proceeds to the next example:
486
487 >>> def f(x):
488 ... '''
489 ... >>> x = 12
490 ... >>> print x
491 ... 14
492 ... >>> x/2
493 ... 6
494 ... '''
495 >>> test = doctest.DocTestFinder().find(f)[0]
496 >>> doctest.DocTestRunner(verbose=True).run(test)
497 Trying: x = 12
498 Expecting: nothing
499 ok
500 Trying: print x
501 Expecting: 14
502 **********************************************************************
503 Failure in example: print x
504 from line #2 of f
505 Expected: 14
506 Got: 12
507 Trying: x/2
508 Expecting: 6
509 ok
510 (1, 3)
511"""
512 def verbose_flag(): r"""
513The `verbose` flag makes the test runner generate more detailed
514output:
515
516 >>> def f(x):
517 ... '''
518 ... >>> x = 12
519 ... >>> print x
520 ... 12
521 ... >>> x/2
522 ... 6
523 ... '''
524 >>> test = doctest.DocTestFinder().find(f)[0]
525
526 >>> doctest.DocTestRunner(verbose=True).run(test)
527 Trying: x = 12
528 Expecting: nothing
529 ok
530 Trying: print x
531 Expecting: 12
532 ok
533 Trying: x/2
534 Expecting: 6
535 ok
536 (0, 3)
537
538If the `verbose` flag is unspecified, then the output will be verbose
539iff `-v` appears in sys.argv:
540
541 >>> # Save the real sys.argv list.
542 >>> old_argv = sys.argv
543
544 >>> # If -v does not appear in sys.argv, then output isn't verbose.
545 >>> sys.argv = ['test']
546 >>> doctest.DocTestRunner().run(test)
547 (0, 3)
548
549 >>> # If -v does appear in sys.argv, then output is verbose.
550 >>> sys.argv = ['test', '-v']
551 >>> doctest.DocTestRunner().run(test)
552 Trying: x = 12
553 Expecting: nothing
554 ok
555 Trying: print x
556 Expecting: 12
557 ok
558 Trying: x/2
559 Expecting: 6
560 ok
561 (0, 3)
562
563 >>> # Restore sys.argv
564 >>> sys.argv = old_argv
565
566In the remaining examples, the test runner's verbosity will be
567explicitly set, to ensure that the test behavior is consistent.
568 """
569 def exceptions(): r"""
570Tests of `DocTestRunner`'s exception handling.
571
572An expected exception is specified with a traceback message. The
573lines between the first line and the type/value may be omitted or
574replaced with any other string:
575
576 >>> def f(x):
577 ... '''
578 ... >>> x = 12
579 ... >>> print x/0
580 ... Traceback (most recent call last):
581 ... ZeroDivisionError: integer division or modulo by zero
582 ... '''
583 >>> test = doctest.DocTestFinder().find(f)[0]
584 >>> doctest.DocTestRunner(verbose=False).run(test)
585 (0, 2)
586
587An example may generate output before it raises an exception; if it
588does, then the output must match the expected output:
589
590 >>> def f(x):
591 ... '''
592 ... >>> x = 12
593 ... >>> print 'pre-exception output', x/0
594 ... pre-exception output
595 ... Traceback (most recent call last):
596 ... ZeroDivisionError: integer division or modulo by zero
597 ... '''
598 >>> test = doctest.DocTestFinder().find(f)[0]
599 >>> doctest.DocTestRunner(verbose=False).run(test)
600 (0, 2)
601
602Exception messages may contain newlines:
603
604 >>> def f(x):
605 ... r'''
606 ... >>> raise ValueError, 'multi\nline\nmessage'
607 ... Traceback (most recent call last):
608 ... ValueError: multi
609 ... line
610 ... message
611 ... '''
612 >>> test = doctest.DocTestFinder().find(f)[0]
613 >>> doctest.DocTestRunner(verbose=False).run(test)
614 (0, 1)
615
616If an exception is expected, but an exception with the wrong type or
617message is raised, then it is reported as a failure:
618
619 >>> def f(x):
620 ... r'''
621 ... >>> raise ValueError, 'message'
622 ... Traceback (most recent call last):
623 ... ValueError: wrong message
624 ... '''
625 >>> test = doctest.DocTestFinder().find(f)[0]
626 >>> doctest.DocTestRunner(verbose=False).run(test)
627 **********************************************************************
628 Failure in example: raise ValueError, 'message'
629 from line #1 of f
630 Expected:
631 Traceback (most recent call last):
632 ValueError: wrong message
633 Got:
634 Traceback (most recent call last):
635 ValueError: message
636 (1, 1)
637
638If an exception is raised but not expected, then it is reported as an
639unexpected exception:
640
641 >>> # Allow ellipsis in the following examples (since the filename
642 >>> # and line number in the traceback can vary):
643 >>> doctest: +ELLIPSIS
644
645 >>> def f(x):
646 ... r'''
647 ... >>> 1/0
648 ... 0
649 ... '''
650 >>> test = doctest.DocTestFinder().find(f)[0]
651 >>> doctest.DocTestRunner(verbose=False).run(test)
652 **********************************************************************
653 Failure in example: 1/0
654 from line #1 of f
655 Exception raised:
656 Traceback (most recent call last):
657 ...
658 ZeroDivisionError: integer division or modulo by zero
659 (1, 1)
660
661 >>> doctest: -ELLIPSIS # Turn ellipsis back off:
662"""
663 def optionflags(): r"""
664Tests of `DocTestRunner`'s option flag handling.
665
666Several option flags can be used to customize the behavior of the test
667runner. These are defined as module constants in doctest, and passed
668to the DocTestRunner constructor (multiple constants should be or-ed
669together).
670
671The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
672and 1/0:
673
674 >>> def f(x):
675 ... '>>> True\n1\n'
676
677 >>> # Without the flag:
678 >>> test = doctest.DocTestFinder().find(f)[0]
679 >>> doctest.DocTestRunner(verbose=False).run(test)
680 (0, 1)
681
682 >>> # With the flag:
683 >>> test = doctest.DocTestFinder().find(f)[0]
684 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
685 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
686 **********************************************************************
687 Failure in example: True
688 from line #0 of f
689 Expected: 1
690 Got: True
691 (1, 1)
692
693The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
694and the '<BLANKLINE>' marker:
695
696 >>> def f(x):
697 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
698
699 >>> # Without the flag:
700 >>> test = doctest.DocTestFinder().find(f)[0]
701 >>> doctest.DocTestRunner(verbose=False).run(test)
702 (0, 1)
703
704 >>> # With the flag:
705 >>> test = doctest.DocTestFinder().find(f)[0]
706 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
707 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
708 **********************************************************************
709 Failure in example: print "a\n\nb"
710 from line #0 of f
711 Expected:
712 a
713 <BLANKLINE>
714 b
715 Got:
716 a
717 <BLANKLINE>
718 b
719 (1, 1)
720
721The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
722treated as equal:
723
724 >>> def f(x):
725 ... '>>> print 1, 2, 3\n 1 2\n 3'
726
727 >>> # Without the flag:
728 >>> test = doctest.DocTestFinder().find(f)[0]
729 >>> doctest.DocTestRunner(verbose=False).run(test)
730 **********************************************************************
731 Failure in example: print 1, 2, 3
732 from line #0 of f
733 Expected:
734 1 2
735 3
736 Got: 1 2 3
737 (1, 1)
738
739 >>> # With the flag:
740 >>> test = doctest.DocTestFinder().find(f)[0]
741 >>> flags = doctest.NORMALIZE_WHITESPACE
742 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
743 (0, 1)
744
745The ELLIPSIS flag causes ellipsis marker ("...") in the expected
746output to match any substring in the actual output:
747
748 >>> def f(x):
749 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
750
751 >>> # Without the flag:
752 >>> test = doctest.DocTestFinder().find(f)[0]
753 >>> doctest.DocTestRunner(verbose=False).run(test)
754 **********************************************************************
755 Failure in example: print range(15)
756 from line #0 of f
757 Expected: [0, 1, 2, ..., 14]
758 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
759 (1, 1)
760
761 >>> # With the flag:
762 >>> test = doctest.DocTestFinder().find(f)[0]
763 >>> flags = doctest.ELLIPSIS
764 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
765 (0, 1)
766
767The UNIFIED_DIFF flag causes failures that involve multi-line expected
768and actual outputs to be displayed using a unified diff:
769
770 >>> def f(x):
771 ... r'''
772 ... >>> print '\n'.join('abcdefg')
773 ... a
774 ... B
775 ... c
776 ... d
777 ... f
778 ... g
779 ... h
780 ... '''
781
782 >>> # Without the flag:
783 >>> test = doctest.DocTestFinder().find(f)[0]
784 >>> doctest.DocTestRunner(verbose=False).run(test)
785 **********************************************************************
786 Failure in example: print '\n'.join('abcdefg')
787 from line #1 of f
788 Expected:
789 a
790 B
791 c
792 d
793 f
794 g
795 h
796 Got:
797 a
798 b
799 c
800 d
801 e
802 f
803 g
804 (1, 1)
805
806 >>> # With the flag:
807 >>> test = doctest.DocTestFinder().find(f)[0]
808 >>> flags = doctest.UNIFIED_DIFF
809 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
810 **********************************************************************
811 Failure in example: print '\n'.join('abcdefg')
812 from line #1 of f
813 Differences (unified diff):
814 --- Expected
815 +++ Got
816 @@ -1,8 +1,8 @@
817 a
818 -B
819 +b
820 c
821 d
822 +e
823 f
824 g
825 -h
826 <BLANKLINE>
827 (1, 1)
828
829The CONTEXT_DIFF flag causes failures that involve multi-line expected
830and actual outputs to be displayed using a context diff:
831
832 >>> # Reuse f() from the UNIFIED_DIFF example, above.
833 >>> test = doctest.DocTestFinder().find(f)[0]
834 >>> flags = doctest.CONTEXT_DIFF
835 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
836 **********************************************************************
837 Failure in example: print '\n'.join('abcdefg')
838 from line #1 of f
839 Differences (context diff):
840 *** Expected
841 --- Got
842 ***************
843 *** 1,8 ****
844 a
845 ! B
846 c
847 d
848 f
849 g
850 - h
851 <BLANKLINE>
852 --- 1,8 ----
853 a
854 ! b
855 c
856 d
857 + e
858 f
859 g
860 <BLANKLINE>
861 (1, 1)
862"""
863 def option_directives(): r"""
864Tests of `DocTestRunner`'s option directive mechanism.
865
866Option directives can be used to turn option flags on or off from
867within a DocTest case. The following example shows how a flag can be
868turned on and off. Note that comments on the same line as the option
869directive are ignored.
870
871 >>> def f(x): r'''
872 ... >>> print range(10) # Should fail: no ellipsis
873 ... [0, 1, ..., 9]
874 ...
875 ... >>> doctest: +ELLIPSIS # turn ellipsis on.
876 ... >>> print range(10) # Should succeed
877 ... [0, 1, ..., 9]
878 ...
879 ... >>> doctest: -ELLIPSIS # turn ellipsis back off.
880 ... >>> print range(10) # Should fail: no ellipsis
881 ... [0, 1, ..., 9]
882 ... '''
883 >>> test = doctest.DocTestFinder().find(f)[0]
884 >>> doctest.DocTestRunner(verbose=False).run(test)
885 **********************************************************************
886 Failure in example: print range(10) # Should fail: no ellipsis
887 from line #1 of f
888 Expected: [0, 1, ..., 9]
889 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
890 **********************************************************************
891 Failure in example: print range(10) # Should fail: no ellipsis
892 from line #9 of f
893 Expected: [0, 1, ..., 9]
894 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
895 (2, 3)
896
897Multiple flags can be toggled by a single option directive:
898
899 >>> def f(x): r'''
900 ... >>> print range(10) # Should fail
901 ... [0, 1, ..., 9]
902 ... >>> doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
903 ... >>> print range(10) # Should succeed
904 ... [0, 1, ..., 9]
905 ... '''
906 >>> test = doctest.DocTestFinder().find(f)[0]
907 >>> doctest.DocTestRunner(verbose=False).run(test)
908 **********************************************************************
909 Failure in example: print range(10) # Should fail
910 from line #1 of f
911 Expected: [0, 1, ..., 9]
912 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
913 (1, 2)
914"""
915
916def test_testsource(): r"""
917Unit tests for `testsource()`.
918
919The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +0000920test with that name in that module, and converts it to a script. The
921example code is converted to regular Python code. The surrounding
922words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +0000923
924 >>> import test.test_doctest
925 >>> name = 'test.test_doctest.sample_func'
926 >>> print doctest.testsource(test.test_doctest, name)
Tim Peters19397e52004-08-06 22:02:59 +0000927 # Blah blah
928 #
Tim Peters8485b562004-08-04 18:46:34 +0000929 print sample_func(22)
930 # Expected:
931 # 44
Tim Peters19397e52004-08-06 22:02:59 +0000932 #
933 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +0000934
935 >>> name = 'test.test_doctest.SampleNewStyleClass'
936 >>> print doctest.testsource(test.test_doctest, name)
937 print '1\n2\n3'
938 # Expected:
939 # 1
940 # 2
941 # 3
942
943 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
944 >>> print doctest.testsource(test.test_doctest, name)
945 print SampleClass.a_classmethod(10)
946 # Expected:
947 # 12
948 print SampleClass(0).a_classmethod(10)
949 # Expected:
950 # 12
951"""
952
953def test_debug(): r"""
954
955Create a docstring that we want to debug:
956
957 >>> s = '''
958 ... >>> x = 12
959 ... >>> print x
960 ... 12
961 ... '''
962
963Create some fake stdin input, to feed to the debugger:
964
965 >>> import tempfile
966 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
967 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
968 >>> fake_stdin.seek(0)
969 >>> real_stdin = sys.stdin
970 >>> sys.stdin = fake_stdin
971
972Run the debugger on the docstring, and then restore sys.stdin.
973
974 >>> doctest: +NORMALIZE_WHITESPACE
975 >>> try:
976 ... doctest.debug_src(s)
977 ... finally:
978 ... sys.stdin = real_stdin
979 ... fake_stdin.close()
980 > <string>(1)?()
981 (Pdb) 12
982 --Return--
983 > <string>(1)?()->None
984 (Pdb) 12
985 (Pdb)
986
987"""
988
Jim Fulton356fd192004-08-09 11:34:47 +0000989def test_pdb_set_trace():
990 r"""Using pdb.set_trace from a doctest
991
Tim Peters413ced62004-08-09 15:43:47 +0000992 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +0000993 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +0000994 you use it. The doctest module changes sys.stdout so that it can
995 capture program output. It also temporarily replaces pdb.set_trace
996 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +0000997 see debugger output.
998
999 >>> doc = '''
1000 ... >>> x = 42
1001 ... >>> import pdb; pdb.set_trace()
1002 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001003 >>> parser = doctest.DocTestParser()
1004 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001005 >>> runner = doctest.DocTestRunner(verbose=False)
1006
1007 To demonstrate this, we'll create a fake standard input that
1008 captures our debugger input:
1009
1010 >>> import tempfile
1011 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1012 >>> fake_stdin.write('\n'.join([
1013 ... 'up', # up out of pdb.set_trace
1014 ... 'up', # up again to get out of our wrapper
1015 ... 'print x', # print data defined by the example
1016 ... 'continue', # stop debugging
1017 ... '']))
1018 >>> fake_stdin.seek(0)
1019 >>> real_stdin = sys.stdin
1020 >>> sys.stdin = fake_stdin
1021
1022 >>> doctest: +ELLIPSIS
1023 >>> runner.run(test)
1024 --Return--
1025 > ...set_trace()->None
1026 -> Pdb().set_trace()
1027 (Pdb) > ...set_trace()
1028 -> real_pdb_set_trace()
1029 (Pdb) > <string>(1)?()
1030 (Pdb) 42
1031 (Pdb) (0, 2)
1032
1033 >>> sys.stdin = real_stdin
1034 >>> fake_stdin.close()
1035
1036 You can also put pdb.set_trace in a function called from a test:
1037
1038 >>> def calls_set_trace():
1039 ... y=2
1040 ... import pdb; pdb.set_trace()
1041
1042 >>> doc = '''
1043 ... >>> x=1
1044 ... >>> calls_set_trace()
1045 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001046 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Tim Peters413ced62004-08-09 15:43:47 +00001047
Jim Fulton356fd192004-08-09 11:34:47 +00001048 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1049 >>> fake_stdin.write('\n'.join([
1050 ... 'up', # up out of pdb.set_trace
1051 ... 'up', # up again to get out of our wrapper
1052 ... 'print y', # print data defined in the function
1053 ... 'up', # out of function
1054 ... 'print x', # print data defined by the example
1055 ... 'continue', # stop debugging
1056 ... '']))
1057 >>> fake_stdin.seek(0)
1058 >>> real_stdin = sys.stdin
1059 >>> sys.stdin = fake_stdin
1060
1061 >>> runner.run(test)
1062 --Return--
1063 > ...set_trace()->None
1064 -> Pdb().set_trace()
1065 (Pdb) ...set_trace()
1066 -> real_pdb_set_trace()
1067 (Pdb) > <string>(3)calls_set_trace()
1068 (Pdb) 2
1069 (Pdb) > <string>(1)?()
1070 (Pdb) 1
1071 (Pdb) (0, 2)
1072
1073 >>> doctest: -ELLIPSIS
1074 """
1075
Tim Peters19397e52004-08-06 22:02:59 +00001076def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001077 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001078
1079 We create a Suite by providing a module. A module can be provided
1080 by passing a module object:
1081
1082 >>> import unittest
1083 >>> import test.sample_doctest
1084 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1085 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001086 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001087
1088 We can also supply the module by name:
1089
1090 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1091 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001092 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001093
1094 We can use the current module:
1095
1096 >>> suite = test.sample_doctest.test_suite()
1097 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001098 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001099
1100 We can supply global variables. If we pass globs, they will be
1101 used instead of the module globals. Here we'll pass an empty
1102 globals, triggering an extra error:
1103
1104 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1105 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001106 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001107
1108 Alternatively, we can provide extra globals. Here we'll make an
1109 error go away by providing an extra global variable:
1110
1111 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1112 ... extraglobs={'y': 1})
1113 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001114 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001115
1116 You can pass option flags. Here we'll cause an extra error
1117 by disabling the blank-line feature:
1118
1119 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001120 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001121 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001122 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001123
Tim Peters1e277ee2004-08-07 05:37:52 +00001124 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001125
1126 >>> def setUp():
1127 ... import test.test_doctest
1128 ... test.test_doctest.sillySetup = True
1129
1130 >>> def tearDown():
1131 ... import test.test_doctest
1132 ... del test.test_doctest.sillySetup
1133
1134 Here, we installed a silly variable that the test expects:
1135
1136 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1137 ... setUp=setUp, tearDown=tearDown)
1138 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001139 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001140
1141 But the tearDown restores sanity:
1142
1143 >>> import test.test_doctest
1144 >>> test.test_doctest.sillySetup
1145 Traceback (most recent call last):
1146 ...
1147 AttributeError: 'module' object has no attribute 'sillySetup'
1148
1149 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001150 use a custom test_finder to to run just the test named bar.
1151 However, the test in the module docstring, and the two tests
1152 in the module __test__ dict, aren't filtered, so we actually
1153 run three tests besides bar's. The filtering mechanisms are
1154 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001155
1156 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001157 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001158 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1159 ... test_finder=finder)
1160 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001161 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001162 """
1163
1164def test_DocFileSuite():
1165 """We can test tests found in text files using a DocFileSuite.
1166
1167 We create a suite by providing the names of one or more text
1168 files that include examples:
1169
1170 >>> import unittest
1171 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1172 ... 'test_doctest2.txt')
1173 >>> suite.run(unittest.TestResult())
1174 <unittest.TestResult run=2 errors=0 failures=2>
1175
1176 The test files are looked for in the directory containing the
1177 calling module. A package keyword argument can be provided to
1178 specify a different relative location.
1179
1180 >>> import unittest
1181 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1182 ... 'test_doctest2.txt',
1183 ... package='test')
1184 >>> suite.run(unittest.TestResult())
1185 <unittest.TestResult run=2 errors=0 failures=2>
1186
1187 Note that '/' should be used as a path separator. It will be
1188 converted to a native separator at run time:
1189
1190
1191 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1192 >>> suite.run(unittest.TestResult())
1193 <unittest.TestResult run=1 errors=0 failures=1>
1194
1195 You can specify initial global variables:
1196
1197 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1198 ... 'test_doctest2.txt',
1199 ... globs={'favorite_color': 'blue'})
1200 >>> suite.run(unittest.TestResult())
1201 <unittest.TestResult run=2 errors=0 failures=1>
1202
1203 In this case, we supplied a missing favorite color. You can
1204 provide doctest options:
1205
1206 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1207 ... 'test_doctest2.txt',
1208 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1209 ... globs={'favorite_color': 'blue'})
1210 >>> suite.run(unittest.TestResult())
1211 <unittest.TestResult run=2 errors=0 failures=2>
1212
1213 And, you can provide setUp and tearDown functions:
1214
1215 You can supply setUp and teatDoen functions:
1216
1217 >>> def setUp():
1218 ... import test.test_doctest
1219 ... test.test_doctest.sillySetup = True
1220
1221 >>> def tearDown():
1222 ... import test.test_doctest
1223 ... del test.test_doctest.sillySetup
1224
1225 Here, we installed a silly variable that the test expects:
1226
1227 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1228 ... 'test_doctest2.txt',
1229 ... setUp=setUp, tearDown=tearDown)
1230 >>> suite.run(unittest.TestResult())
1231 <unittest.TestResult run=2 errors=0 failures=1>
1232
1233 But the tearDown restores sanity:
1234
1235 >>> import test.test_doctest
1236 >>> test.test_doctest.sillySetup
1237 Traceback (most recent call last):
1238 ...
1239 AttributeError: 'module' object has no attribute 'sillySetup'
1240
1241 """
1242
1243
Tim Peters8485b562004-08-04 18:46:34 +00001244######################################################################
1245## Main
1246######################################################################
1247
1248def test_main():
1249 # Check the doctest cases in doctest itself:
1250 test_support.run_doctest(doctest, verbosity=True)
1251 # Check the doctest cases defined here:
1252 from test import test_doctest
1253 test_support.run_doctest(test_doctest, verbosity=True)
1254
1255import trace, sys, re, StringIO
1256def test_coverage(coverdir):
1257 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1258 trace=0, count=1)
1259 tracer.run('reload(doctest); test_main()')
1260 r = tracer.results()
1261 print 'Writing coverage results...'
1262 r.write_results(show_missing=True, summary=True,
1263 coverdir=coverdir)
1264
1265if __name__ == '__main__':
1266 if '-c' in sys.argv:
1267 test_coverage('/tmp/doctest.cover')
1268 else:
1269 test_main()