blob: 6d9d745a04f6ac53cbba2cb9c8931ed523d3ac23 [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
286
287
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)
934"""
935 def option_directives(): r"""
936Tests of `DocTestRunner`'s option directive mechanism.
937
Edward Loper74bca7a2004-08-12 02:27:44 +0000938Option directives can be used to turn option flags on or off for a
939single example. To turn an option on for an example, follow that
940example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +0000941
942 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +0000943 ... >>> print range(10) # should fail: no ellipsis
944 ... [0, 1, ..., 9]
945 ...
946 ... >>> print range(10) # doctest: +ELLIPSIS
947 ... [0, 1, ..., 9]
948 ... '''
949 >>> test = doctest.DocTestFinder().find(f)[0]
950 >>> doctest.DocTestRunner(verbose=False).run(test)
951 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000952 Line 2, in f
953 Failed example:
954 print range(10) # should fail: no ellipsis
955 Expected:
956 [0, 1, ..., 9]
957 Got:
958 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +0000959 (1, 2)
960
961To turn an option off for an example, follow that example with a
962comment of the form ``# doctest: -OPTION``:
963
964 >>> def f(x): r'''
965 ... >>> print range(10)
966 ... [0, 1, ..., 9]
967 ...
968 ... >>> # should fail: no ellipsis
969 ... >>> print range(10) # doctest: -ELLIPSIS
970 ... [0, 1, ..., 9]
971 ... '''
972 >>> test = doctest.DocTestFinder().find(f)[0]
973 >>> doctest.DocTestRunner(verbose=False,
974 ... optionflags=doctest.ELLIPSIS).run(test)
975 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000976 Line 6, in f
977 Failed example:
978 print range(10) # doctest: -ELLIPSIS
979 Expected:
980 [0, 1, ..., 9]
981 Got:
982 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +0000983 (1, 2)
984
985Option directives affect only the example that they appear with; they
986do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +0000987
Edward Loper74bca7a2004-08-12 02:27:44 +0000988 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +0000989 ... >>> print range(10) # Should fail: no ellipsis
990 ... [0, 1, ..., 9]
991 ...
Edward Loper74bca7a2004-08-12 02:27:44 +0000992 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000993 ... [0, 1, ..., 9]
994 ...
Tim Peters8485b562004-08-04 18:46:34 +0000995 ... >>> print range(10) # Should fail: no ellipsis
996 ... [0, 1, ..., 9]
997 ... '''
998 >>> test = doctest.DocTestFinder().find(f)[0]
999 >>> doctest.DocTestRunner(verbose=False).run(test)
1000 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001001 Line 2, in f
1002 Failed example:
1003 print range(10) # Should fail: no ellipsis
1004 Expected:
1005 [0, 1, ..., 9]
1006 Got:
1007 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001008 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001009 Line 8, in f
1010 Failed example:
1011 print range(10) # Should fail: no ellipsis
1012 Expected:
1013 [0, 1, ..., 9]
1014 Got:
1015 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001016 (2, 3)
1017
Edward Loper74bca7a2004-08-12 02:27:44 +00001018Multiple options may be modified by a single option directive. They
1019may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001020
1021 >>> def f(x): r'''
1022 ... >>> print range(10) # Should fail
1023 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001024 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001025 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001026 ... [0, 1, ..., 9]
1027 ... '''
1028 >>> test = doctest.DocTestFinder().find(f)[0]
1029 >>> doctest.DocTestRunner(verbose=False).run(test)
1030 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001031 Line 2, in f
1032 Failed example:
1033 print range(10) # Should fail
1034 Expected:
1035 [0, 1, ..., 9]
1036 Got:
1037 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001038 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001039
1040 >>> def f(x): r'''
1041 ... >>> print range(10) # Should fail
1042 ... [0, 1, ..., 9]
1043 ... >>> print range(10) # Should succeed
1044 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1045 ... [0, 1, ..., 9]
1046 ... '''
1047 >>> test = doctest.DocTestFinder().find(f)[0]
1048 >>> doctest.DocTestRunner(verbose=False).run(test)
1049 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001050 Line 2, in f
1051 Failed example:
1052 print range(10) # Should fail
1053 Expected:
1054 [0, 1, ..., 9]
1055 Got:
1056 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001057 (1, 2)
1058
1059 >>> def f(x): r'''
1060 ... >>> print range(10) # Should fail
1061 ... [0, 1, ..., 9]
1062 ... >>> print range(10) # Should succeed
1063 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1064 ... [0, 1, ..., 9]
1065 ... '''
1066 >>> test = doctest.DocTestFinder().find(f)[0]
1067 >>> doctest.DocTestRunner(verbose=False).run(test)
1068 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001069 Line 2, in f
1070 Failed example:
1071 print range(10) # Should fail
1072 Expected:
1073 [0, 1, ..., 9]
1074 Got:
1075 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001076 (1, 2)
1077
1078The option directive may be put on the line following the source, as
1079long as a continuation prompt is used:
1080
1081 >>> def f(x): r'''
1082 ... >>> print range(10)
1083 ... ... # doctest: +ELLIPSIS
1084 ... [0, 1, ..., 9]
1085 ... '''
1086 >>> test = doctest.DocTestFinder().find(f)[0]
1087 >>> doctest.DocTestRunner(verbose=False).run(test)
1088 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001089
Edward Loper74bca7a2004-08-12 02:27:44 +00001090For examples with multi-line source, the option directive may appear
1091at the end of any line:
1092
1093 >>> def f(x): r'''
1094 ... >>> for x in range(10): # doctest: +ELLIPSIS
1095 ... ... print x,
1096 ... 0 1 2 ... 9
1097 ...
1098 ... >>> for x in range(10):
1099 ... ... print x, # doctest: +ELLIPSIS
1100 ... 0 1 2 ... 9
1101 ... '''
1102 >>> test = doctest.DocTestFinder().find(f)[0]
1103 >>> doctest.DocTestRunner(verbose=False).run(test)
1104 (0, 2)
1105
1106If more than one line of an example with multi-line source has an
1107option directive, then they are combined:
1108
1109 >>> def f(x): r'''
1110 ... Should fail (option directive not on the last line):
1111 ... >>> for x in range(10): # doctest: +ELLIPSIS
1112 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1113 ... 0 1 2...9
1114 ... '''
1115 >>> test = doctest.DocTestFinder().find(f)[0]
1116 >>> doctest.DocTestRunner(verbose=False).run(test)
1117 (0, 1)
1118
1119It is an error to have a comment of the form ``# doctest:`` that is
1120*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1121``OPTION`` is an option that has been registered with
1122`register_option`:
1123
1124 >>> # Error: Option not registered
1125 >>> s = '>>> print 12 #doctest: +BADOPTION'
1126 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1127 Traceback (most recent call last):
1128 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1129
1130 >>> # Error: No + or - prefix
1131 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1132 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1133 Traceback (most recent call last):
1134 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1135
1136It is an error to use an option directive on a line that contains no
1137source:
1138
1139 >>> s = '>>> # doctest: +ELLIPSIS'
1140 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1141 Traceback (most recent call last):
1142 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 +00001143"""
1144
1145def test_testsource(): r"""
1146Unit tests for `testsource()`.
1147
1148The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001149test with that name in that module, and converts it to a script. The
1150example code is converted to regular Python code. The surrounding
1151words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001152
1153 >>> import test.test_doctest
1154 >>> name = 'test.test_doctest.sample_func'
1155 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001156 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001157 #
Tim Peters8485b562004-08-04 18:46:34 +00001158 print sample_func(22)
1159 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001160 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001161 #
Edward Lopera5db6002004-08-12 02:41:30 +00001162 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001163
1164 >>> name = 'test.test_doctest.SampleNewStyleClass'
1165 >>> print doctest.testsource(test.test_doctest, name)
1166 print '1\n2\n3'
1167 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001168 ## 1
1169 ## 2
1170 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001171
1172 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1173 >>> print doctest.testsource(test.test_doctest, name)
1174 print SampleClass.a_classmethod(10)
1175 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001176 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001177 print SampleClass(0).a_classmethod(10)
1178 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001179 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001180"""
1181
1182def test_debug(): r"""
1183
1184Create a docstring that we want to debug:
1185
1186 >>> s = '''
1187 ... >>> x = 12
1188 ... >>> print x
1189 ... 12
1190 ... '''
1191
1192Create some fake stdin input, to feed to the debugger:
1193
1194 >>> import tempfile
1195 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1196 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1197 >>> fake_stdin.seek(0)
1198 >>> real_stdin = sys.stdin
1199 >>> sys.stdin = fake_stdin
1200
1201Run the debugger on the docstring, and then restore sys.stdin.
1202
Tim Peters8485b562004-08-04 18:46:34 +00001203 >>> try:
1204 ... doctest.debug_src(s)
1205 ... finally:
1206 ... sys.stdin = real_stdin
1207 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001208 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001209 > <string>(1)?()
1210 (Pdb) 12
1211 --Return--
1212 > <string>(1)?()->None
1213 (Pdb) 12
1214 (Pdb)
1215
1216"""
1217
Jim Fulton356fd192004-08-09 11:34:47 +00001218def test_pdb_set_trace():
1219 r"""Using pdb.set_trace from a doctest
1220
Tim Peters413ced62004-08-09 15:43:47 +00001221 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001222 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001223 you use it. The doctest module changes sys.stdout so that it can
1224 capture program output. It also temporarily replaces pdb.set_trace
1225 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001226 see debugger output.
1227
1228 >>> doc = '''
1229 ... >>> x = 42
1230 ... >>> import pdb; pdb.set_trace()
1231 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001232 >>> parser = doctest.DocTestParser()
1233 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001234 >>> runner = doctest.DocTestRunner(verbose=False)
1235
1236 To demonstrate this, we'll create a fake standard input that
1237 captures our debugger input:
1238
1239 >>> import tempfile
1240 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1241 >>> fake_stdin.write('\n'.join([
1242 ... 'up', # up out of pdb.set_trace
1243 ... 'up', # up again to get out of our wrapper
1244 ... 'print x', # print data defined by the example
1245 ... 'continue', # stop debugging
1246 ... '']))
1247 >>> fake_stdin.seek(0)
1248 >>> real_stdin = sys.stdin
1249 >>> sys.stdin = fake_stdin
1250
Edward Loper74bca7a2004-08-12 02:27:44 +00001251 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001252 --Return--
1253 > ...set_trace()->None
1254 -> Pdb().set_trace()
1255 (Pdb) > ...set_trace()
1256 -> real_pdb_set_trace()
1257 (Pdb) > <string>(1)?()
1258 (Pdb) 42
1259 (Pdb) (0, 2)
1260
1261 >>> sys.stdin = real_stdin
1262 >>> fake_stdin.close()
1263
1264 You can also put pdb.set_trace in a function called from a test:
1265
1266 >>> def calls_set_trace():
1267 ... y=2
1268 ... import pdb; pdb.set_trace()
1269
1270 >>> doc = '''
1271 ... >>> x=1
1272 ... >>> calls_set_trace()
1273 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001274 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001275 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1276 >>> fake_stdin.write('\n'.join([
1277 ... 'up', # up out of pdb.set_trace
1278 ... 'up', # up again to get out of our wrapper
1279 ... 'print y', # print data defined in the function
1280 ... 'up', # out of function
1281 ... 'print x', # print data defined by the example
1282 ... 'continue', # stop debugging
1283 ... '']))
1284 >>> fake_stdin.seek(0)
1285 >>> real_stdin = sys.stdin
1286 >>> sys.stdin = fake_stdin
1287
Edward Loper74bca7a2004-08-12 02:27:44 +00001288 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001289 --Return--
1290 > ...set_trace()->None
1291 -> Pdb().set_trace()
1292 (Pdb) ...set_trace()
1293 -> real_pdb_set_trace()
1294 (Pdb) > <string>(3)calls_set_trace()
1295 (Pdb) 2
1296 (Pdb) > <string>(1)?()
1297 (Pdb) 1
1298 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001299 """
1300
Tim Peters19397e52004-08-06 22:02:59 +00001301def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001302 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001303
1304 We create a Suite by providing a module. A module can be provided
1305 by passing a module object:
1306
1307 >>> import unittest
1308 >>> import test.sample_doctest
1309 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1310 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001311 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001312
1313 We can also supply the module by name:
1314
1315 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1316 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001317 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001318
1319 We can use the current module:
1320
1321 >>> suite = test.sample_doctest.test_suite()
1322 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001323 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001324
1325 We can supply global variables. If we pass globs, they will be
1326 used instead of the module globals. Here we'll pass an empty
1327 globals, triggering an extra error:
1328
1329 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1330 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001331 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001332
1333 Alternatively, we can provide extra globals. Here we'll make an
1334 error go away by providing an extra global variable:
1335
1336 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1337 ... extraglobs={'y': 1})
1338 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001339 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001340
1341 You can pass option flags. Here we'll cause an extra error
1342 by disabling the blank-line feature:
1343
1344 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001345 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001346 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001347 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001348
Tim Peters1e277ee2004-08-07 05:37:52 +00001349 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001350
1351 >>> def setUp():
1352 ... import test.test_doctest
1353 ... test.test_doctest.sillySetup = True
1354
1355 >>> def tearDown():
1356 ... import test.test_doctest
1357 ... del test.test_doctest.sillySetup
1358
1359 Here, we installed a silly variable that the test expects:
1360
1361 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1362 ... setUp=setUp, tearDown=tearDown)
1363 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001364 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001365
1366 But the tearDown restores sanity:
1367
1368 >>> import test.test_doctest
1369 >>> test.test_doctest.sillySetup
1370 Traceback (most recent call last):
1371 ...
1372 AttributeError: 'module' object has no attribute 'sillySetup'
1373
1374 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001375 use a custom test_finder to to run just the test named bar.
1376 However, the test in the module docstring, and the two tests
1377 in the module __test__ dict, aren't filtered, so we actually
1378 run three tests besides bar's. The filtering mechanisms are
1379 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001380
1381 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001382 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001383 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1384 ... test_finder=finder)
1385 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001386 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001387 """
1388
1389def test_DocFileSuite():
1390 """We can test tests found in text files using a DocFileSuite.
1391
1392 We create a suite by providing the names of one or more text
1393 files that include examples:
1394
1395 >>> import unittest
1396 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1397 ... 'test_doctest2.txt')
1398 >>> suite.run(unittest.TestResult())
1399 <unittest.TestResult run=2 errors=0 failures=2>
1400
1401 The test files are looked for in the directory containing the
1402 calling module. A package keyword argument can be provided to
1403 specify a different relative location.
1404
1405 >>> import unittest
1406 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1407 ... 'test_doctest2.txt',
1408 ... package='test')
1409 >>> suite.run(unittest.TestResult())
1410 <unittest.TestResult run=2 errors=0 failures=2>
1411
1412 Note that '/' should be used as a path separator. It will be
1413 converted to a native separator at run time:
1414
1415
1416 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1417 >>> suite.run(unittest.TestResult())
1418 <unittest.TestResult run=1 errors=0 failures=1>
1419
1420 You can specify initial global variables:
1421
1422 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1423 ... 'test_doctest2.txt',
1424 ... globs={'favorite_color': 'blue'})
1425 >>> suite.run(unittest.TestResult())
1426 <unittest.TestResult run=2 errors=0 failures=1>
1427
1428 In this case, we supplied a missing favorite color. You can
1429 provide doctest options:
1430
1431 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1432 ... 'test_doctest2.txt',
1433 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1434 ... globs={'favorite_color': 'blue'})
1435 >>> suite.run(unittest.TestResult())
1436 <unittest.TestResult run=2 errors=0 failures=2>
1437
1438 And, you can provide setUp and tearDown functions:
1439
1440 You can supply setUp and teatDoen functions:
1441
1442 >>> def setUp():
1443 ... import test.test_doctest
1444 ... test.test_doctest.sillySetup = True
1445
1446 >>> def tearDown():
1447 ... import test.test_doctest
1448 ... del test.test_doctest.sillySetup
1449
1450 Here, we installed a silly variable that the test expects:
1451
1452 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1453 ... 'test_doctest2.txt',
1454 ... setUp=setUp, tearDown=tearDown)
1455 >>> suite.run(unittest.TestResult())
1456 <unittest.TestResult run=2 errors=0 failures=1>
1457
1458 But the tearDown restores sanity:
1459
1460 >>> import test.test_doctest
1461 >>> test.test_doctest.sillySetup
1462 Traceback (most recent call last):
1463 ...
1464 AttributeError: 'module' object has no attribute 'sillySetup'
1465
1466 """
1467
Jim Fulton07a349c2004-08-22 14:10:00 +00001468def test_trailing_space_in_test():
1469 """
1470 Trailing spaces in expcted output are significant:
1471
1472 >>> x, y = 'foo', ''
1473 >>> print x, y
1474 foo \n
1475 """
Tim Peters19397e52004-08-06 22:02:59 +00001476
Tim Peters8485b562004-08-04 18:46:34 +00001477######################################################################
1478## Main
1479######################################################################
1480
1481def test_main():
1482 # Check the doctest cases in doctest itself:
1483 test_support.run_doctest(doctest, verbosity=True)
1484 # Check the doctest cases defined here:
1485 from test import test_doctest
1486 test_support.run_doctest(test_doctest, verbosity=True)
1487
1488import trace, sys, re, StringIO
1489def test_coverage(coverdir):
1490 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1491 trace=0, count=1)
1492 tracer.run('reload(doctest); test_main()')
1493 r = tracer.results()
1494 print 'Writing coverage results...'
1495 r.write_results(show_missing=True, summary=True,
1496 coverdir=coverdir)
1497
1498if __name__ == '__main__':
1499 if '-c' in sys.argv:
1500 test_coverage('/tmp/doctest.cover')
1501 else:
1502 test_main()