blob: 969ee17efc996e66244ebb7c14ea618cc4d38a57 [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
Tim Peters8485b562004-08-04 18:46:34 +0000256def test_DocTestFinder(): r"""
257Unit tests for the `DocTestFinder` class.
258
259DocTestFinder is used to extract DocTests from an object's docstring
260and the docstrings of its contained objects. It can be used with
261modules, functions, classes, methods, staticmethods, classmethods, and
262properties.
263
264Finding Tests in Functions
265~~~~~~~~~~~~~~~~~~~~~~~~~~
266For a function whose docstring contains examples, DocTestFinder.find()
267will return a single test (for that function's docstring):
268
Tim Peters8485b562004-08-04 18:46:34 +0000269 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000270
271We'll simulate a __file__ attr that ends in pyc:
272
273 >>> import test.test_doctest
274 >>> old = test.test_doctest.__file__
275 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
276
Tim Peters8485b562004-08-04 18:46:34 +0000277 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000278
Edward Loper74bca7a2004-08-12 02:27:44 +0000279 >>> print tests # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000280 [<DocTest sample_func from ...:12 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000281
Jim Fulton07a349c2004-08-22 14:10:00 +0000282 >>> tests[0].filename
283 'test_doctest.py'
284
285 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000286
Jim Fulton07a349c2004-08-22 14:10:00 +0000287
Tim Peters8485b562004-08-04 18:46:34 +0000288 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000289 >>> (e.source, e.want, e.lineno)
290 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000291
Tim Peters8485b562004-08-04 18:46:34 +0000292If an object has no docstring, then a test is not created for it:
293
294 >>> def no_docstring(v):
295 ... pass
296 >>> finder.find(no_docstring)
297 []
298
299If the function has a docstring with no examples, then a test with no
300examples is returned. (This lets `DocTestRunner` collect statistics
301about which functions have no tests -- but is that useful? And should
302an empty test also be created when there's no docstring?)
303
304 >>> def no_examples(v):
305 ... ''' no doctest examples '''
306 >>> finder.find(no_examples)
307 [<DocTest no_examples from None:1 (no examples)>]
308
309Finding Tests in Classes
310~~~~~~~~~~~~~~~~~~~~~~~~
311For a class, DocTestFinder will create a test for the class's
312docstring, and will recursively explore its contents, including
313methods, classmethods, staticmethods, properties, and nested classes.
314
315 >>> finder = doctest.DocTestFinder()
316 >>> tests = finder.find(SampleClass)
317 >>> tests.sort()
318 >>> for t in tests:
319 ... print '%2s %s' % (len(t.examples), t.name)
320 1 SampleClass
321 3 SampleClass.NestedClass
322 1 SampleClass.NestedClass.__init__
323 1 SampleClass.__init__
324 2 SampleClass.a_classmethod
325 1 SampleClass.a_property
326 1 SampleClass.a_staticmethod
327 1 SampleClass.double
328 1 SampleClass.get
329
330New-style classes are also supported:
331
332 >>> tests = finder.find(SampleNewStyleClass)
333 >>> tests.sort()
334 >>> for t in tests:
335 ... print '%2s %s' % (len(t.examples), t.name)
336 1 SampleNewStyleClass
337 1 SampleNewStyleClass.__init__
338 1 SampleNewStyleClass.double
339 1 SampleNewStyleClass.get
340
341Finding Tests in Modules
342~~~~~~~~~~~~~~~~~~~~~~~~
343For a module, DocTestFinder will create a test for the class's
344docstring, and will recursively explore its contents, including
345functions, classes, and the `__test__` dictionary, if it exists:
346
347 >>> # A module
348 >>> import new
349 >>> m = new.module('some_module')
350 >>> def triple(val):
351 ... '''
352 ... >>> print tripple(11)
353 ... 33
354 ... '''
355 ... return val*3
356 >>> m.__dict__.update({
357 ... 'sample_func': sample_func,
358 ... 'SampleClass': SampleClass,
359 ... '__doc__': '''
360 ... Module docstring.
361 ... >>> print 'module'
362 ... module
363 ... ''',
364 ... '__test__': {
365 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
366 ... 'c': triple}})
367
368 >>> finder = doctest.DocTestFinder()
369 >>> # Use module=test.test_doctest, to prevent doctest from
370 >>> # ignoring the objects since they weren't defined in m.
371 >>> import test.test_doctest
372 >>> tests = finder.find(m, module=test.test_doctest)
373 >>> tests.sort()
374 >>> for t in tests:
375 ... print '%2s %s' % (len(t.examples), t.name)
376 1 some_module
377 1 some_module.SampleClass
378 3 some_module.SampleClass.NestedClass
379 1 some_module.SampleClass.NestedClass.__init__
380 1 some_module.SampleClass.__init__
381 2 some_module.SampleClass.a_classmethod
382 1 some_module.SampleClass.a_property
383 1 some_module.SampleClass.a_staticmethod
384 1 some_module.SampleClass.double
385 1 some_module.SampleClass.get
386 1 some_module.c
387 2 some_module.d
388 1 some_module.sample_func
389
390Duplicate Removal
391~~~~~~~~~~~~~~~~~
392If a single object is listed twice (under different names), then tests
393will only be generated for it once:
394
Tim Petersf3f57472004-08-08 06:11:48 +0000395 >>> from test import doctest_aliases
396 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000397 >>> tests.sort()
398 >>> print len(tests)
399 2
400 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000401 test.doctest_aliases.TwoNames
402
403 TwoNames.f and TwoNames.g are bound to the same object.
404 We can't guess which will be found in doctest's traversal of
405 TwoNames.__dict__ first, so we have to allow for either.
406
407 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000408 True
409
410Filter Functions
411~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000412A filter function can be used to restrict which objects get examined,
413but this is temporary, undocumented internal support for testmod's
414deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000415
416 >>> def namefilter(prefix, base):
417 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000418 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000419 >>> tests.sort()
420 >>> for t in tests:
421 ... print '%2s %s' % (len(t.examples), t.name)
422 1 SampleClass
423 3 SampleClass.NestedClass
424 1 SampleClass.NestedClass.__init__
425 1 SampleClass.__init__
426 1 SampleClass.double
427 1 SampleClass.get
428
Tim Peters8485b562004-08-04 18:46:34 +0000429If a given object is filtered out, then none of the objects that it
430contains will be added either:
431
432 >>> def namefilter(prefix, base):
433 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000434 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000435 >>> tests.sort()
436 >>> for t in tests:
437 ... print '%2s %s' % (len(t.examples), t.name)
438 1 SampleClass
439 1 SampleClass.__init__
440 2 SampleClass.a_classmethod
441 1 SampleClass.a_property
442 1 SampleClass.a_staticmethod
443 1 SampleClass.double
444 1 SampleClass.get
445
Tim Petersf727c6c2004-08-08 01:48:59 +0000446The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000447object explicitly passed to DocTestFinder:
448
449 >>> def namefilter(prefix, base):
450 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000451 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000452 >>> len(tests)
453 9
454
455Turning off Recursion
456~~~~~~~~~~~~~~~~~~~~~
457DocTestFinder can be told not to look for tests in contained objects
458using the `recurse` flag:
459
460 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
461 >>> tests.sort()
462 >>> for t in tests:
463 ... print '%2s %s' % (len(t.examples), t.name)
464 1 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000465
466Line numbers
467~~~~~~~~~~~~
468DocTestFinder finds the line number of each example:
469
470 >>> def f(x):
471 ... '''
472 ... >>> x = 12
473 ...
474 ... some text
475 ...
476 ... >>> # examples are not created for comments & bare prompts.
477 ... >>>
478 ... ...
479 ...
480 ... >>> for x in range(10):
481 ... ... print x,
482 ... 0 1 2 3 4 5 6 7 8 9
483 ... >>> x/2
484 ... 6
485 ... '''
486 >>> test = doctest.DocTestFinder().find(f)[0]
487 >>> [e.lineno for e in test.examples]
488 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000489"""
490
491class test_DocTestRunner:
492 def basics(): r"""
493Unit tests for the `DocTestRunner` class.
494
495DocTestRunner is used to run DocTest test cases, and to accumulate
496statistics. Here's a simple DocTest case we can use:
497
498 >>> def f(x):
499 ... '''
500 ... >>> x = 12
501 ... >>> print x
502 ... 12
503 ... >>> x/2
504 ... 6
505 ... '''
506 >>> test = doctest.DocTestFinder().find(f)[0]
507
508The main DocTestRunner interface is the `run` method, which runs a
509given DocTest case in a given namespace (globs). It returns a tuple
510`(f,t)`, where `f` is the number of failed tests and `t` is the number
511of tried tests.
512
513 >>> doctest.DocTestRunner(verbose=False).run(test)
514 (0, 3)
515
516If any example produces incorrect output, then the test runner reports
517the failure and proceeds to the next example:
518
519 >>> def f(x):
520 ... '''
521 ... >>> x = 12
522 ... >>> print x
523 ... 14
524 ... >>> x/2
525 ... 6
526 ... '''
527 >>> test = doctest.DocTestFinder().find(f)[0]
528 >>> doctest.DocTestRunner(verbose=True).run(test)
529 Trying: x = 12
530 Expecting: nothing
531 ok
532 Trying: print x
533 Expecting: 14
534 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000535 Line 3, in f
536 Failed example:
537 print x
538 Expected:
539 14
540 Got:
541 12
Tim Peters8485b562004-08-04 18:46:34 +0000542 Trying: x/2
543 Expecting: 6
544 ok
545 (1, 3)
546"""
547 def verbose_flag(): r"""
548The `verbose` flag makes the test runner generate more detailed
549output:
550
551 >>> def f(x):
552 ... '''
553 ... >>> x = 12
554 ... >>> print x
555 ... 12
556 ... >>> x/2
557 ... 6
558 ... '''
559 >>> test = doctest.DocTestFinder().find(f)[0]
560
561 >>> doctest.DocTestRunner(verbose=True).run(test)
562 Trying: x = 12
563 Expecting: nothing
564 ok
565 Trying: print x
566 Expecting: 12
567 ok
568 Trying: x/2
569 Expecting: 6
570 ok
571 (0, 3)
572
573If the `verbose` flag is unspecified, then the output will be verbose
574iff `-v` appears in sys.argv:
575
576 >>> # Save the real sys.argv list.
577 >>> old_argv = sys.argv
578
579 >>> # If -v does not appear in sys.argv, then output isn't verbose.
580 >>> sys.argv = ['test']
581 >>> doctest.DocTestRunner().run(test)
582 (0, 3)
583
584 >>> # If -v does appear in sys.argv, then output is verbose.
585 >>> sys.argv = ['test', '-v']
586 >>> doctest.DocTestRunner().run(test)
587 Trying: x = 12
588 Expecting: nothing
589 ok
590 Trying: print x
591 Expecting: 12
592 ok
593 Trying: x/2
594 Expecting: 6
595 ok
596 (0, 3)
597
598 >>> # Restore sys.argv
599 >>> sys.argv = old_argv
600
601In the remaining examples, the test runner's verbosity will be
602explicitly set, to ensure that the test behavior is consistent.
603 """
604 def exceptions(): r"""
605Tests of `DocTestRunner`'s exception handling.
606
607An expected exception is specified with a traceback message. The
608lines between the first line and the type/value may be omitted or
609replaced with any other string:
610
611 >>> def f(x):
612 ... '''
613 ... >>> x = 12
614 ... >>> print x/0
615 ... Traceback (most recent call last):
616 ... ZeroDivisionError: integer division or modulo by zero
617 ... '''
618 >>> test = doctest.DocTestFinder().find(f)[0]
619 >>> doctest.DocTestRunner(verbose=False).run(test)
620 (0, 2)
621
622An example may generate output before it raises an exception; if it
623does, then the output must match the expected output:
624
625 >>> def f(x):
626 ... '''
627 ... >>> x = 12
628 ... >>> print 'pre-exception output', x/0
629 ... pre-exception output
630 ... Traceback (most recent call last):
631 ... ZeroDivisionError: integer division or modulo by zero
632 ... '''
633 >>> test = doctest.DocTestFinder().find(f)[0]
634 >>> doctest.DocTestRunner(verbose=False).run(test)
635 (0, 2)
636
637Exception messages may contain newlines:
638
639 >>> def f(x):
640 ... r'''
641 ... >>> raise ValueError, 'multi\nline\nmessage'
642 ... Traceback (most recent call last):
643 ... ValueError: multi
644 ... line
645 ... message
646 ... '''
647 >>> test = doctest.DocTestFinder().find(f)[0]
648 >>> doctest.DocTestRunner(verbose=False).run(test)
649 (0, 1)
650
651If an exception is expected, but an exception with the wrong type or
652message is raised, then it is reported as a failure:
653
654 >>> def f(x):
655 ... r'''
656 ... >>> raise ValueError, 'message'
657 ... Traceback (most recent call last):
658 ... ValueError: wrong message
659 ... '''
660 >>> test = doctest.DocTestFinder().find(f)[0]
661 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000662 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000663 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000664 Line 2, in f
665 Failed example:
666 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000667 Expected:
668 Traceback (most recent call last):
669 ValueError: wrong message
670 Got:
671 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000672 ...
Tim Peters8485b562004-08-04 18:46:34 +0000673 ValueError: message
674 (1, 1)
675
676If an exception is raised but not expected, then it is reported as an
677unexpected exception:
678
Tim Peters8485b562004-08-04 18:46:34 +0000679 >>> def f(x):
680 ... r'''
681 ... >>> 1/0
682 ... 0
683 ... '''
684 >>> test = doctest.DocTestFinder().find(f)[0]
685 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000686 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000687 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000688 Line 2, in f
689 Failed example:
690 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000691 Exception raised:
692 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000693 ...
Tim Peters8485b562004-08-04 18:46:34 +0000694 ZeroDivisionError: integer division or modulo by zero
695 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000696"""
697 def optionflags(): r"""
698Tests of `DocTestRunner`'s option flag handling.
699
700Several option flags can be used to customize the behavior of the test
701runner. These are defined as module constants in doctest, and passed
702to the DocTestRunner constructor (multiple constants should be or-ed
703together).
704
705The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
706and 1/0:
707
708 >>> def f(x):
709 ... '>>> True\n1\n'
710
711 >>> # Without the flag:
712 >>> test = doctest.DocTestFinder().find(f)[0]
713 >>> doctest.DocTestRunner(verbose=False).run(test)
714 (0, 1)
715
716 >>> # With the flag:
717 >>> test = doctest.DocTestFinder().find(f)[0]
718 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
719 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
720 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000721 Line 1, in f
722 Failed example:
723 True
724 Expected:
725 1
726 Got:
727 True
Tim Peters8485b562004-08-04 18:46:34 +0000728 (1, 1)
729
730The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
731and the '<BLANKLINE>' marker:
732
733 >>> def f(x):
734 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
735
736 >>> # Without the flag:
737 >>> test = doctest.DocTestFinder().find(f)[0]
738 >>> doctest.DocTestRunner(verbose=False).run(test)
739 (0, 1)
740
741 >>> # With the flag:
742 >>> test = doctest.DocTestFinder().find(f)[0]
743 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
744 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
745 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000746 Line 1, in f
747 Failed example:
748 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000749 Expected:
750 a
751 <BLANKLINE>
752 b
753 Got:
754 a
755 <BLANKLINE>
756 b
757 (1, 1)
758
759The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
760treated as equal:
761
762 >>> def f(x):
763 ... '>>> print 1, 2, 3\n 1 2\n 3'
764
765 >>> # Without the flag:
766 >>> test = doctest.DocTestFinder().find(f)[0]
767 >>> doctest.DocTestRunner(verbose=False).run(test)
768 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000769 Line 1, in f
770 Failed example:
771 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000772 Expected:
773 1 2
774 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000775 Got:
776 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000777 (1, 1)
778
779 >>> # With the flag:
780 >>> test = doctest.DocTestFinder().find(f)[0]
781 >>> flags = doctest.NORMALIZE_WHITESPACE
782 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
783 (0, 1)
784
Tim Peters026f8dc2004-08-19 16:38:58 +0000785 An example from the docs:
786 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
787 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
788 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
789
Tim Peters8485b562004-08-04 18:46:34 +0000790The ELLIPSIS flag causes ellipsis marker ("...") in the expected
791output to match any substring in the actual output:
792
793 >>> def f(x):
794 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
795
796 >>> # Without the flag:
797 >>> test = doctest.DocTestFinder().find(f)[0]
798 >>> doctest.DocTestRunner(verbose=False).run(test)
799 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000800 Line 1, in f
801 Failed example:
802 print range(15)
803 Expected:
804 [0, 1, 2, ..., 14]
805 Got:
806 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +0000807 (1, 1)
808
809 >>> # With the flag:
810 >>> test = doctest.DocTestFinder().find(f)[0]
811 >>> flags = doctest.ELLIPSIS
812 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
813 (0, 1)
814
Tim Peterse594bee2004-08-22 01:47:51 +0000815 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +0000816
817 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +0000818 ... print i**2, #doctest: +ELLIPSIS
819 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +0000820
Tim Peters026f8dc2004-08-19 16:38:58 +0000821 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000822
823 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +0000824 ... print i,
825 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +0000826
Tim Peters026f8dc2004-08-19 16:38:58 +0000827 Examples from the docs:
828
829 >>> print range(20) # doctest:+ELLIPSIS
830 [0, 1, ..., 18, 19]
831
832 >>> print range(20) # doctest: +ELLIPSIS
833 ... # doctest: +NORMALIZE_WHITESPACE
834 [0, 1, ..., 18, 19]
835
Tim Peters8485b562004-08-04 18:46:34 +0000836The UNIFIED_DIFF flag causes failures that involve multi-line expected
837and actual outputs to be displayed using a unified diff:
838
839 >>> def f(x):
840 ... r'''
841 ... >>> print '\n'.join('abcdefg')
842 ... a
843 ... B
844 ... c
845 ... d
846 ... f
847 ... g
848 ... h
849 ... '''
850
851 >>> # Without the flag:
852 >>> test = doctest.DocTestFinder().find(f)[0]
853 >>> doctest.DocTestRunner(verbose=False).run(test)
854 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000855 Line 2, in f
856 Failed example:
857 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000858 Expected:
859 a
860 B
861 c
862 d
863 f
864 g
865 h
866 Got:
867 a
868 b
869 c
870 d
871 e
872 f
873 g
874 (1, 1)
875
876 >>> # With the flag:
877 >>> test = doctest.DocTestFinder().find(f)[0]
878 >>> flags = doctest.UNIFIED_DIFF
879 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
880 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000881 Line 2, in f
882 Failed example:
883 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000884 Differences (unified diff):
885 --- Expected
886 +++ Got
887 @@ -1,8 +1,8 @@
888 a
889 -B
890 +b
891 c
892 d
893 +e
894 f
895 g
896 -h
897 <BLANKLINE>
898 (1, 1)
899
900The CONTEXT_DIFF flag causes failures that involve multi-line expected
901and actual outputs to be displayed using a context diff:
902
903 >>> # Reuse f() from the UNIFIED_DIFF example, above.
904 >>> test = doctest.DocTestFinder().find(f)[0]
905 >>> flags = doctest.CONTEXT_DIFF
906 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
907 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000908 Line 2, in f
909 Failed example:
910 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000911 Differences (context diff):
912 *** Expected
913 --- Got
914 ***************
915 *** 1,8 ****
916 a
917 ! B
918 c
919 d
920 f
921 g
922 - h
923 <BLANKLINE>
924 --- 1,8 ----
925 a
926 ! b
927 c
928 d
929 + e
930 f
931 g
932 <BLANKLINE>
933 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +0000934
935
936The NDIFF_DIFF flag causes failures to use the difflib.Differ algorithm
937used by the popular ndiff.py utility. This does intraline difference
938marking, as well as interline differences.
939
940 >>> def f(x):
941 ... r'''
942 ... >>> print "a b c d e f g h i j k l m"
943 ... a b c d e f g h i j k 1 m
944 ... '''
945 >>> test = doctest.DocTestFinder().find(f)[0]
946 >>> flags = doctest.NDIFF_DIFF
947 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
948 **********************************************************************
949 Line 2, in f
950 Failed example:
951 print "a b c d e f g h i j k l m"
952 Differences (ndiff with -expected +actual):
953 - a b c d e f g h i j k 1 m
954 ? ^
955 + a b c d e f g h i j k l m
956 ? + ++ ^
957 <BLANKLINE>
958 (1, 1)
959 """
960
Tim Peters8485b562004-08-04 18:46:34 +0000961 def option_directives(): r"""
962Tests of `DocTestRunner`'s option directive mechanism.
963
Edward Loper74bca7a2004-08-12 02:27:44 +0000964Option directives can be used to turn option flags on or off for a
965single example. To turn an option on for an example, follow that
966example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +0000967
968 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +0000969 ... >>> print range(10) # should fail: no ellipsis
970 ... [0, 1, ..., 9]
971 ...
972 ... >>> print range(10) # doctest: +ELLIPSIS
973 ... [0, 1, ..., 9]
974 ... '''
975 >>> test = doctest.DocTestFinder().find(f)[0]
976 >>> doctest.DocTestRunner(verbose=False).run(test)
977 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000978 Line 2, in f
979 Failed example:
980 print range(10) # should fail: no ellipsis
981 Expected:
982 [0, 1, ..., 9]
983 Got:
984 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +0000985 (1, 2)
986
987To turn an option off for an example, follow that example with a
988comment of the form ``# doctest: -OPTION``:
989
990 >>> def f(x): r'''
991 ... >>> print range(10)
992 ... [0, 1, ..., 9]
993 ...
994 ... >>> # should fail: no ellipsis
995 ... >>> print range(10) # doctest: -ELLIPSIS
996 ... [0, 1, ..., 9]
997 ... '''
998 >>> test = doctest.DocTestFinder().find(f)[0]
999 >>> doctest.DocTestRunner(verbose=False,
1000 ... optionflags=doctest.ELLIPSIS).run(test)
1001 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001002 Line 6, in f
1003 Failed example:
1004 print range(10) # doctest: -ELLIPSIS
1005 Expected:
1006 [0, 1, ..., 9]
1007 Got:
1008 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001009 (1, 2)
1010
1011Option directives affect only the example that they appear with; they
1012do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001013
Edward Loper74bca7a2004-08-12 02:27:44 +00001014 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001015 ... >>> print range(10) # Should fail: no ellipsis
1016 ... [0, 1, ..., 9]
1017 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001018 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001019 ... [0, 1, ..., 9]
1020 ...
Tim Peters8485b562004-08-04 18:46:34 +00001021 ... >>> print range(10) # Should fail: no ellipsis
1022 ... [0, 1, ..., 9]
1023 ... '''
1024 >>> test = doctest.DocTestFinder().find(f)[0]
1025 >>> doctest.DocTestRunner(verbose=False).run(test)
1026 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001027 Line 2, in f
1028 Failed example:
1029 print range(10) # Should fail: no ellipsis
1030 Expected:
1031 [0, 1, ..., 9]
1032 Got:
1033 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001034 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001035 Line 8, in f
1036 Failed example:
1037 print range(10) # Should fail: no ellipsis
1038 Expected:
1039 [0, 1, ..., 9]
1040 Got:
1041 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001042 (2, 3)
1043
Edward Loper74bca7a2004-08-12 02:27:44 +00001044Multiple options may be modified by a single option directive. They
1045may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001046
1047 >>> def f(x): r'''
1048 ... >>> print range(10) # Should fail
1049 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001050 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001051 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001052 ... [0, 1, ..., 9]
1053 ... '''
1054 >>> test = doctest.DocTestFinder().find(f)[0]
1055 >>> doctest.DocTestRunner(verbose=False).run(test)
1056 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001057 Line 2, in f
1058 Failed example:
1059 print range(10) # Should fail
1060 Expected:
1061 [0, 1, ..., 9]
1062 Got:
1063 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001064 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001065
1066 >>> def f(x): r'''
1067 ... >>> print range(10) # Should fail
1068 ... [0, 1, ..., 9]
1069 ... >>> print range(10) # Should succeed
1070 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1071 ... [0, 1, ..., 9]
1072 ... '''
1073 >>> test = doctest.DocTestFinder().find(f)[0]
1074 >>> doctest.DocTestRunner(verbose=False).run(test)
1075 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001076 Line 2, in f
1077 Failed example:
1078 print range(10) # Should fail
1079 Expected:
1080 [0, 1, ..., 9]
1081 Got:
1082 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001083 (1, 2)
1084
1085 >>> def f(x): r'''
1086 ... >>> print range(10) # Should fail
1087 ... [0, 1, ..., 9]
1088 ... >>> print range(10) # Should succeed
1089 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1090 ... [0, 1, ..., 9]
1091 ... '''
1092 >>> test = doctest.DocTestFinder().find(f)[0]
1093 >>> doctest.DocTestRunner(verbose=False).run(test)
1094 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001095 Line 2, in f
1096 Failed example:
1097 print range(10) # Should fail
1098 Expected:
1099 [0, 1, ..., 9]
1100 Got:
1101 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001102 (1, 2)
1103
1104The option directive may be put on the line following the source, as
1105long as a continuation prompt is used:
1106
1107 >>> def f(x): r'''
1108 ... >>> print range(10)
1109 ... ... # doctest: +ELLIPSIS
1110 ... [0, 1, ..., 9]
1111 ... '''
1112 >>> test = doctest.DocTestFinder().find(f)[0]
1113 >>> doctest.DocTestRunner(verbose=False).run(test)
1114 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001115
Edward Loper74bca7a2004-08-12 02:27:44 +00001116For examples with multi-line source, the option directive may appear
1117at the end of any line:
1118
1119 >>> def f(x): r'''
1120 ... >>> for x in range(10): # doctest: +ELLIPSIS
1121 ... ... print x,
1122 ... 0 1 2 ... 9
1123 ...
1124 ... >>> for x in range(10):
1125 ... ... print x, # doctest: +ELLIPSIS
1126 ... 0 1 2 ... 9
1127 ... '''
1128 >>> test = doctest.DocTestFinder().find(f)[0]
1129 >>> doctest.DocTestRunner(verbose=False).run(test)
1130 (0, 2)
1131
1132If more than one line of an example with multi-line source has an
1133option directive, then they are combined:
1134
1135 >>> def f(x): r'''
1136 ... Should fail (option directive not on the last line):
1137 ... >>> for x in range(10): # doctest: +ELLIPSIS
1138 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1139 ... 0 1 2...9
1140 ... '''
1141 >>> test = doctest.DocTestFinder().find(f)[0]
1142 >>> doctest.DocTestRunner(verbose=False).run(test)
1143 (0, 1)
1144
1145It is an error to have a comment of the form ``# doctest:`` that is
1146*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1147``OPTION`` is an option that has been registered with
1148`register_option`:
1149
1150 >>> # Error: Option not registered
1151 >>> s = '>>> print 12 #doctest: +BADOPTION'
1152 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1153 Traceback (most recent call last):
1154 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1155
1156 >>> # Error: No + or - prefix
1157 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1158 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1159 Traceback (most recent call last):
1160 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1161
1162It is an error to use an option directive on a line that contains no
1163source:
1164
1165 >>> s = '>>> # doctest: +ELLIPSIS'
1166 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1167 Traceback (most recent call last):
1168 ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
Tim Peters8485b562004-08-04 18:46:34 +00001169"""
1170
1171def test_testsource(): r"""
1172Unit tests for `testsource()`.
1173
1174The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001175test with that name in that module, and converts it to a script. The
1176example code is converted to regular Python code. The surrounding
1177words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001178
1179 >>> import test.test_doctest
1180 >>> name = 'test.test_doctest.sample_func'
1181 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001182 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001183 #
Tim Peters8485b562004-08-04 18:46:34 +00001184 print sample_func(22)
1185 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001186 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001187 #
Edward Lopera5db6002004-08-12 02:41:30 +00001188 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001189
1190 >>> name = 'test.test_doctest.SampleNewStyleClass'
1191 >>> print doctest.testsource(test.test_doctest, name)
1192 print '1\n2\n3'
1193 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001194 ## 1
1195 ## 2
1196 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001197
1198 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1199 >>> print doctest.testsource(test.test_doctest, name)
1200 print SampleClass.a_classmethod(10)
1201 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001202 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001203 print SampleClass(0).a_classmethod(10)
1204 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001205 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001206"""
1207
1208def test_debug(): r"""
1209
1210Create a docstring that we want to debug:
1211
1212 >>> s = '''
1213 ... >>> x = 12
1214 ... >>> print x
1215 ... 12
1216 ... '''
1217
1218Create some fake stdin input, to feed to the debugger:
1219
1220 >>> import tempfile
1221 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1222 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1223 >>> fake_stdin.seek(0)
1224 >>> real_stdin = sys.stdin
1225 >>> sys.stdin = fake_stdin
1226
1227Run the debugger on the docstring, and then restore sys.stdin.
1228
Tim Peters8485b562004-08-04 18:46:34 +00001229 >>> try:
1230 ... doctest.debug_src(s)
1231 ... finally:
1232 ... sys.stdin = real_stdin
1233 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001234 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001235 > <string>(1)?()
1236 (Pdb) 12
1237 --Return--
1238 > <string>(1)?()->None
1239 (Pdb) 12
1240 (Pdb)
1241
1242"""
1243
Jim Fulton356fd192004-08-09 11:34:47 +00001244def test_pdb_set_trace():
1245 r"""Using pdb.set_trace from a doctest
1246
Tim Peters413ced62004-08-09 15:43:47 +00001247 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001248 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001249 you use it. The doctest module changes sys.stdout so that it can
1250 capture program output. It also temporarily replaces pdb.set_trace
1251 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001252 see debugger output.
1253
1254 >>> doc = '''
1255 ... >>> x = 42
1256 ... >>> import pdb; pdb.set_trace()
1257 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001258 >>> parser = doctest.DocTestParser()
1259 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001260 >>> runner = doctest.DocTestRunner(verbose=False)
1261
1262 To demonstrate this, we'll create a fake standard input that
1263 captures our debugger input:
1264
1265 >>> import tempfile
1266 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1267 >>> fake_stdin.write('\n'.join([
1268 ... 'up', # up out of pdb.set_trace
1269 ... 'up', # up again to get out of our wrapper
1270 ... 'print x', # print data defined by the example
1271 ... 'continue', # stop debugging
1272 ... '']))
1273 >>> fake_stdin.seek(0)
1274 >>> real_stdin = sys.stdin
1275 >>> sys.stdin = fake_stdin
1276
Edward Loper74bca7a2004-08-12 02:27:44 +00001277 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001278 --Return--
1279 > ...set_trace()->None
1280 -> Pdb().set_trace()
1281 (Pdb) > ...set_trace()
1282 -> real_pdb_set_trace()
1283 (Pdb) > <string>(1)?()
1284 (Pdb) 42
1285 (Pdb) (0, 2)
1286
1287 >>> sys.stdin = real_stdin
1288 >>> fake_stdin.close()
1289
1290 You can also put pdb.set_trace in a function called from a test:
1291
1292 >>> def calls_set_trace():
1293 ... y=2
1294 ... import pdb; pdb.set_trace()
1295
1296 >>> doc = '''
1297 ... >>> x=1
1298 ... >>> calls_set_trace()
1299 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001300 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001301 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1302 >>> fake_stdin.write('\n'.join([
1303 ... 'up', # up out of pdb.set_trace
1304 ... 'up', # up again to get out of our wrapper
1305 ... 'print y', # print data defined in the function
1306 ... 'up', # out of function
1307 ... 'print x', # print data defined by the example
1308 ... 'continue', # stop debugging
1309 ... '']))
1310 >>> fake_stdin.seek(0)
1311 >>> real_stdin = sys.stdin
1312 >>> sys.stdin = fake_stdin
1313
Edward Loper74bca7a2004-08-12 02:27:44 +00001314 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001315 --Return--
1316 > ...set_trace()->None
1317 -> Pdb().set_trace()
1318 (Pdb) ...set_trace()
1319 -> real_pdb_set_trace()
1320 (Pdb) > <string>(3)calls_set_trace()
1321 (Pdb) 2
1322 (Pdb) > <string>(1)?()
1323 (Pdb) 1
1324 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001325 """
1326
Tim Peters19397e52004-08-06 22:02:59 +00001327def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001328 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001329
1330 We create a Suite by providing a module. A module can be provided
1331 by passing a module object:
1332
1333 >>> import unittest
1334 >>> import test.sample_doctest
1335 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1336 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001337 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001338
1339 We can also supply the module by name:
1340
1341 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1342 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001343 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001344
1345 We can use the current module:
1346
1347 >>> suite = test.sample_doctest.test_suite()
1348 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001349 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001350
1351 We can supply global variables. If we pass globs, they will be
1352 used instead of the module globals. Here we'll pass an empty
1353 globals, triggering an extra error:
1354
1355 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1356 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001357 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001358
1359 Alternatively, we can provide extra globals. Here we'll make an
1360 error go away by providing an extra global variable:
1361
1362 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1363 ... extraglobs={'y': 1})
1364 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001365 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001366
1367 You can pass option flags. Here we'll cause an extra error
1368 by disabling the blank-line feature:
1369
1370 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001371 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001372 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001373 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001374
Tim Peters1e277ee2004-08-07 05:37:52 +00001375 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001376
1377 >>> def setUp():
1378 ... import test.test_doctest
1379 ... test.test_doctest.sillySetup = True
1380
1381 >>> def tearDown():
1382 ... import test.test_doctest
1383 ... del test.test_doctest.sillySetup
1384
1385 Here, we installed a silly variable that the test expects:
1386
1387 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1388 ... setUp=setUp, tearDown=tearDown)
1389 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001390 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001391
1392 But the tearDown restores sanity:
1393
1394 >>> import test.test_doctest
1395 >>> test.test_doctest.sillySetup
1396 Traceback (most recent call last):
1397 ...
1398 AttributeError: 'module' object has no attribute 'sillySetup'
1399
1400 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001401 use a custom test_finder to to run just the test named bar.
1402 However, the test in the module docstring, and the two tests
1403 in the module __test__ dict, aren't filtered, so we actually
1404 run three tests besides bar's. The filtering mechanisms are
1405 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001406
1407 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001408 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001409 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1410 ... test_finder=finder)
1411 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001412 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001413 """
1414
1415def test_DocFileSuite():
1416 """We can test tests found in text files using a DocFileSuite.
1417
1418 We create a suite by providing the names of one or more text
1419 files that include examples:
1420
1421 >>> import unittest
1422 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1423 ... 'test_doctest2.txt')
1424 >>> suite.run(unittest.TestResult())
1425 <unittest.TestResult run=2 errors=0 failures=2>
1426
1427 The test files are looked for in the directory containing the
1428 calling module. A package keyword argument can be provided to
1429 specify a different relative location.
1430
1431 >>> import unittest
1432 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1433 ... 'test_doctest2.txt',
1434 ... package='test')
1435 >>> suite.run(unittest.TestResult())
1436 <unittest.TestResult run=2 errors=0 failures=2>
1437
1438 Note that '/' should be used as a path separator. It will be
1439 converted to a native separator at run time:
1440
1441
1442 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1443 >>> suite.run(unittest.TestResult())
1444 <unittest.TestResult run=1 errors=0 failures=1>
1445
1446 You can specify initial global variables:
1447
1448 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1449 ... 'test_doctest2.txt',
1450 ... globs={'favorite_color': 'blue'})
1451 >>> suite.run(unittest.TestResult())
1452 <unittest.TestResult run=2 errors=0 failures=1>
1453
1454 In this case, we supplied a missing favorite color. You can
1455 provide doctest options:
1456
1457 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1458 ... 'test_doctest2.txt',
1459 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1460 ... globs={'favorite_color': 'blue'})
1461 >>> suite.run(unittest.TestResult())
1462 <unittest.TestResult run=2 errors=0 failures=2>
1463
1464 And, you can provide setUp and tearDown functions:
1465
1466 You can supply setUp and teatDoen functions:
1467
1468 >>> def setUp():
1469 ... import test.test_doctest
1470 ... test.test_doctest.sillySetup = True
1471
1472 >>> def tearDown():
1473 ... import test.test_doctest
1474 ... del test.test_doctest.sillySetup
1475
1476 Here, we installed a silly variable that the test expects:
1477
1478 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1479 ... 'test_doctest2.txt',
1480 ... setUp=setUp, tearDown=tearDown)
1481 >>> suite.run(unittest.TestResult())
1482 <unittest.TestResult run=2 errors=0 failures=1>
1483
1484 But the tearDown restores sanity:
1485
1486 >>> import test.test_doctest
1487 >>> test.test_doctest.sillySetup
1488 Traceback (most recent call last):
1489 ...
1490 AttributeError: 'module' object has no attribute 'sillySetup'
1491
1492 """
1493
Jim Fulton07a349c2004-08-22 14:10:00 +00001494def test_trailing_space_in_test():
1495 """
1496 Trailing spaces in expcted output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001497
Jim Fulton07a349c2004-08-22 14:10:00 +00001498 >>> x, y = 'foo', ''
1499 >>> print x, y
1500 foo \n
1501 """
Tim Peters19397e52004-08-06 22:02:59 +00001502
Tim Peters8485b562004-08-04 18:46:34 +00001503######################################################################
1504## Main
1505######################################################################
1506
1507def test_main():
1508 # Check the doctest cases in doctest itself:
1509 test_support.run_doctest(doctest, verbosity=True)
1510 # Check the doctest cases defined here:
1511 from test import test_doctest
1512 test_support.run_doctest(test_doctest, verbosity=True)
1513
1514import trace, sys, re, StringIO
1515def test_coverage(coverdir):
1516 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1517 trace=0, count=1)
1518 tracer.run('reload(doctest); test_main()')
1519 r = tracer.results()
1520 print 'Writing coverage results...'
1521 r.write_results(show_missing=True, summary=True,
1522 coverdir=coverdir)
1523
1524if __name__ == '__main__':
1525 if '-c' in sys.argv:
1526 test_coverage('/tmp/doctest.cover')
1527 else:
1528 test_main()