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