blob: 27c3e9224ec7d47d21749b3f2f1557d818062466 [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
Tim Peters19397e52004-08-06 22:02:59 +0000987def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +0000988 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +0000989
990 We create a Suite by providing a module. A module can be provided
991 by passing a module object:
992
993 >>> import unittest
994 >>> import test.sample_doctest
995 >>> suite = doctest.DocTestSuite(test.sample_doctest)
996 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +0000997 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +0000998
999 We can also supply the module by name:
1000
1001 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1002 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001003 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001004
1005 We can use the current module:
1006
1007 >>> suite = test.sample_doctest.test_suite()
1008 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001009 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001010
1011 We can supply global variables. If we pass globs, they will be
1012 used instead of the module globals. Here we'll pass an empty
1013 globals, triggering an extra error:
1014
1015 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1016 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001017 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001018
1019 Alternatively, we can provide extra globals. Here we'll make an
1020 error go away by providing an extra global variable:
1021
1022 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1023 ... extraglobs={'y': 1})
1024 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001025 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001026
1027 You can pass option flags. Here we'll cause an extra error
1028 by disabling the blank-line feature:
1029
1030 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001031 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001032 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001033 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001034
Tim Peters1e277ee2004-08-07 05:37:52 +00001035 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001036
1037 >>> def setUp():
1038 ... import test.test_doctest
1039 ... test.test_doctest.sillySetup = True
1040
1041 >>> def tearDown():
1042 ... import test.test_doctest
1043 ... del test.test_doctest.sillySetup
1044
1045 Here, we installed a silly variable that the test expects:
1046
1047 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1048 ... setUp=setUp, tearDown=tearDown)
1049 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001050 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001051
1052 But the tearDown restores sanity:
1053
1054 >>> import test.test_doctest
1055 >>> test.test_doctest.sillySetup
1056 Traceback (most recent call last):
1057 ...
1058 AttributeError: 'module' object has no attribute 'sillySetup'
1059
1060 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001061 use a custom test_finder to to run just the test named bar.
1062 However, the test in the module docstring, and the two tests
1063 in the module __test__ dict, aren't filtered, so we actually
1064 run three tests besides bar's. The filtering mechanisms are
1065 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001066
1067 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001068 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001069 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1070 ... test_finder=finder)
1071 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001072 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001073 """
1074
1075def test_DocFileSuite():
1076 """We can test tests found in text files using a DocFileSuite.
1077
1078 We create a suite by providing the names of one or more text
1079 files that include examples:
1080
1081 >>> import unittest
1082 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1083 ... 'test_doctest2.txt')
1084 >>> suite.run(unittest.TestResult())
1085 <unittest.TestResult run=2 errors=0 failures=2>
1086
1087 The test files are looked for in the directory containing the
1088 calling module. A package keyword argument can be provided to
1089 specify a different relative location.
1090
1091 >>> import unittest
1092 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1093 ... 'test_doctest2.txt',
1094 ... package='test')
1095 >>> suite.run(unittest.TestResult())
1096 <unittest.TestResult run=2 errors=0 failures=2>
1097
1098 Note that '/' should be used as a path separator. It will be
1099 converted to a native separator at run time:
1100
1101
1102 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1103 >>> suite.run(unittest.TestResult())
1104 <unittest.TestResult run=1 errors=0 failures=1>
1105
1106 You can specify initial global variables:
1107
1108 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1109 ... 'test_doctest2.txt',
1110 ... globs={'favorite_color': 'blue'})
1111 >>> suite.run(unittest.TestResult())
1112 <unittest.TestResult run=2 errors=0 failures=1>
1113
1114 In this case, we supplied a missing favorite color. You can
1115 provide doctest options:
1116
1117 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1118 ... 'test_doctest2.txt',
1119 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1120 ... globs={'favorite_color': 'blue'})
1121 >>> suite.run(unittest.TestResult())
1122 <unittest.TestResult run=2 errors=0 failures=2>
1123
1124 And, you can provide setUp and tearDown functions:
1125
1126 You can supply setUp and teatDoen functions:
1127
1128 >>> def setUp():
1129 ... import test.test_doctest
1130 ... test.test_doctest.sillySetup = True
1131
1132 >>> def tearDown():
1133 ... import test.test_doctest
1134 ... del test.test_doctest.sillySetup
1135
1136 Here, we installed a silly variable that the test expects:
1137
1138 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1139 ... 'test_doctest2.txt',
1140 ... setUp=setUp, tearDown=tearDown)
1141 >>> suite.run(unittest.TestResult())
1142 <unittest.TestResult run=2 errors=0 failures=1>
1143
1144 But the tearDown restores sanity:
1145
1146 >>> import test.test_doctest
1147 >>> test.test_doctest.sillySetup
1148 Traceback (most recent call last):
1149 ...
1150 AttributeError: 'module' object has no attribute 'sillySetup'
1151
1152 """
1153
1154
Tim Peters8485b562004-08-04 18:46:34 +00001155######################################################################
1156## Main
1157######################################################################
1158
1159def test_main():
1160 # Check the doctest cases in doctest itself:
1161 test_support.run_doctest(doctest, verbosity=True)
1162 # Check the doctest cases defined here:
1163 from test import test_doctest
1164 test_support.run_doctest(test_doctest, verbosity=True)
1165
1166import trace, sys, re, StringIO
1167def test_coverage(coverdir):
1168 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1169 trace=0, count=1)
1170 tracer.run('reload(doctest); test_main()')
1171 r = tracer.results()
1172 print 'Writing coverage results...'
1173 r.write_results(show_missing=True, summary=True,
1174 coverdir=coverdir)
1175
1176if __name__ == '__main__':
1177 if '-c' in sys.argv:
1178 test_coverage('/tmp/doctest.cover')
1179 else:
1180 test_main()