blob: 3c5fa084d46260323c2248e930289729ef508c77 [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()
270 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000271
Edward Loper74bca7a2004-08-12 02:27:44 +0000272 >>> print tests # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000273 [<DocTest sample_func from ...:12 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000274
Tim Peters8485b562004-08-04 18:46:34 +0000275 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000276 >>> (e.source, e.want, e.lineno)
277 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000278
Tim Peters8485b562004-08-04 18:46:34 +0000279If an object has no docstring, then a test is not created for it:
280
281 >>> def no_docstring(v):
282 ... pass
283 >>> finder.find(no_docstring)
284 []
285
286If the function has a docstring with no examples, then a test with no
287examples is returned. (This lets `DocTestRunner` collect statistics
288about which functions have no tests -- but is that useful? And should
289an empty test also be created when there's no docstring?)
290
291 >>> def no_examples(v):
292 ... ''' no doctest examples '''
293 >>> finder.find(no_examples)
294 [<DocTest no_examples from None:1 (no examples)>]
295
296Finding Tests in Classes
297~~~~~~~~~~~~~~~~~~~~~~~~
298For a class, DocTestFinder will create a test for the class's
299docstring, and will recursively explore its contents, including
300methods, classmethods, staticmethods, properties, and nested classes.
301
302 >>> finder = doctest.DocTestFinder()
303 >>> tests = finder.find(SampleClass)
304 >>> tests.sort()
305 >>> for t in tests:
306 ... print '%2s %s' % (len(t.examples), t.name)
307 1 SampleClass
308 3 SampleClass.NestedClass
309 1 SampleClass.NestedClass.__init__
310 1 SampleClass.__init__
311 2 SampleClass.a_classmethod
312 1 SampleClass.a_property
313 1 SampleClass.a_staticmethod
314 1 SampleClass.double
315 1 SampleClass.get
316
317New-style classes are also supported:
318
319 >>> tests = finder.find(SampleNewStyleClass)
320 >>> tests.sort()
321 >>> for t in tests:
322 ... print '%2s %s' % (len(t.examples), t.name)
323 1 SampleNewStyleClass
324 1 SampleNewStyleClass.__init__
325 1 SampleNewStyleClass.double
326 1 SampleNewStyleClass.get
327
328Finding Tests in Modules
329~~~~~~~~~~~~~~~~~~~~~~~~
330For a module, DocTestFinder will create a test for the class's
331docstring, and will recursively explore its contents, including
332functions, classes, and the `__test__` dictionary, if it exists:
333
334 >>> # A module
335 >>> import new
336 >>> m = new.module('some_module')
337 >>> def triple(val):
338 ... '''
339 ... >>> print tripple(11)
340 ... 33
341 ... '''
342 ... return val*3
343 >>> m.__dict__.update({
344 ... 'sample_func': sample_func,
345 ... 'SampleClass': SampleClass,
346 ... '__doc__': '''
347 ... Module docstring.
348 ... >>> print 'module'
349 ... module
350 ... ''',
351 ... '__test__': {
352 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
353 ... 'c': triple}})
354
355 >>> finder = doctest.DocTestFinder()
356 >>> # Use module=test.test_doctest, to prevent doctest from
357 >>> # ignoring the objects since they weren't defined in m.
358 >>> import test.test_doctest
359 >>> tests = finder.find(m, module=test.test_doctest)
360 >>> tests.sort()
361 >>> for t in tests:
362 ... print '%2s %s' % (len(t.examples), t.name)
363 1 some_module
364 1 some_module.SampleClass
365 3 some_module.SampleClass.NestedClass
366 1 some_module.SampleClass.NestedClass.__init__
367 1 some_module.SampleClass.__init__
368 2 some_module.SampleClass.a_classmethod
369 1 some_module.SampleClass.a_property
370 1 some_module.SampleClass.a_staticmethod
371 1 some_module.SampleClass.double
372 1 some_module.SampleClass.get
373 1 some_module.c
374 2 some_module.d
375 1 some_module.sample_func
376
377Duplicate Removal
378~~~~~~~~~~~~~~~~~
379If a single object is listed twice (under different names), then tests
380will only be generated for it once:
381
Tim Petersf3f57472004-08-08 06:11:48 +0000382 >>> from test import doctest_aliases
383 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000384 >>> tests.sort()
385 >>> print len(tests)
386 2
387 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000388 test.doctest_aliases.TwoNames
389
390 TwoNames.f and TwoNames.g are bound to the same object.
391 We can't guess which will be found in doctest's traversal of
392 TwoNames.__dict__ first, so we have to allow for either.
393
394 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000395 True
396
397Filter Functions
398~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000399A filter function can be used to restrict which objects get examined,
400but this is temporary, undocumented internal support for testmod's
401deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000402
403 >>> def namefilter(prefix, base):
404 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000405 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000406 >>> tests.sort()
407 >>> for t in tests:
408 ... print '%2s %s' % (len(t.examples), t.name)
409 1 SampleClass
410 3 SampleClass.NestedClass
411 1 SampleClass.NestedClass.__init__
412 1 SampleClass.__init__
413 1 SampleClass.double
414 1 SampleClass.get
415
Tim Peters8485b562004-08-04 18:46:34 +0000416If a given object is filtered out, then none of the objects that it
417contains will be added either:
418
419 >>> def namefilter(prefix, base):
420 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000421 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000422 >>> tests.sort()
423 >>> for t in tests:
424 ... print '%2s %s' % (len(t.examples), t.name)
425 1 SampleClass
426 1 SampleClass.__init__
427 2 SampleClass.a_classmethod
428 1 SampleClass.a_property
429 1 SampleClass.a_staticmethod
430 1 SampleClass.double
431 1 SampleClass.get
432
Tim Petersf727c6c2004-08-08 01:48:59 +0000433The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000434object explicitly passed to DocTestFinder:
435
436 >>> def namefilter(prefix, base):
437 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000438 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000439 >>> len(tests)
440 9
441
442Turning off Recursion
443~~~~~~~~~~~~~~~~~~~~~
444DocTestFinder can be told not to look for tests in contained objects
445using the `recurse` flag:
446
447 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
448 >>> tests.sort()
449 >>> for t in tests:
450 ... print '%2s %s' % (len(t.examples), t.name)
451 1 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000452
453Line numbers
454~~~~~~~~~~~~
455DocTestFinder finds the line number of each example:
456
457 >>> def f(x):
458 ... '''
459 ... >>> x = 12
460 ...
461 ... some text
462 ...
463 ... >>> # examples are not created for comments & bare prompts.
464 ... >>>
465 ... ...
466 ...
467 ... >>> for x in range(10):
468 ... ... print x,
469 ... 0 1 2 3 4 5 6 7 8 9
470 ... >>> x/2
471 ... 6
472 ... '''
473 >>> test = doctest.DocTestFinder().find(f)[0]
474 >>> [e.lineno for e in test.examples]
475 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000476"""
477
478class test_DocTestRunner:
479 def basics(): r"""
480Unit tests for the `DocTestRunner` class.
481
482DocTestRunner is used to run DocTest test cases, and to accumulate
483statistics. Here's a simple DocTest case we can use:
484
485 >>> def f(x):
486 ... '''
487 ... >>> x = 12
488 ... >>> print x
489 ... 12
490 ... >>> x/2
491 ... 6
492 ... '''
493 >>> test = doctest.DocTestFinder().find(f)[0]
494
495The main DocTestRunner interface is the `run` method, which runs a
496given DocTest case in a given namespace (globs). It returns a tuple
497`(f,t)`, where `f` is the number of failed tests and `t` is the number
498of tried tests.
499
500 >>> doctest.DocTestRunner(verbose=False).run(test)
501 (0, 3)
502
503If any example produces incorrect output, then the test runner reports
504the failure and proceeds to the next example:
505
506 >>> def f(x):
507 ... '''
508 ... >>> x = 12
509 ... >>> print x
510 ... 14
511 ... >>> x/2
512 ... 6
513 ... '''
514 >>> test = doctest.DocTestFinder().find(f)[0]
515 >>> doctest.DocTestRunner(verbose=True).run(test)
516 Trying: x = 12
517 Expecting: nothing
518 ok
519 Trying: print x
520 Expecting: 14
521 **********************************************************************
522 Failure in example: print x
523 from line #2 of f
524 Expected: 14
525 Got: 12
526 Trying: x/2
527 Expecting: 6
528 ok
529 (1, 3)
530"""
531 def verbose_flag(): r"""
532The `verbose` flag makes the test runner generate more detailed
533output:
534
535 >>> def f(x):
536 ... '''
537 ... >>> x = 12
538 ... >>> print x
539 ... 12
540 ... >>> x/2
541 ... 6
542 ... '''
543 >>> test = doctest.DocTestFinder().find(f)[0]
544
545 >>> doctest.DocTestRunner(verbose=True).run(test)
546 Trying: x = 12
547 Expecting: nothing
548 ok
549 Trying: print x
550 Expecting: 12
551 ok
552 Trying: x/2
553 Expecting: 6
554 ok
555 (0, 3)
556
557If the `verbose` flag is unspecified, then the output will be verbose
558iff `-v` appears in sys.argv:
559
560 >>> # Save the real sys.argv list.
561 >>> old_argv = sys.argv
562
563 >>> # If -v does not appear in sys.argv, then output isn't verbose.
564 >>> sys.argv = ['test']
565 >>> doctest.DocTestRunner().run(test)
566 (0, 3)
567
568 >>> # If -v does appear in sys.argv, then output is verbose.
569 >>> sys.argv = ['test', '-v']
570 >>> doctest.DocTestRunner().run(test)
571 Trying: x = 12
572 Expecting: nothing
573 ok
574 Trying: print x
575 Expecting: 12
576 ok
577 Trying: x/2
578 Expecting: 6
579 ok
580 (0, 3)
581
582 >>> # Restore sys.argv
583 >>> sys.argv = old_argv
584
585In the remaining examples, the test runner's verbosity will be
586explicitly set, to ensure that the test behavior is consistent.
587 """
588 def exceptions(): r"""
589Tests of `DocTestRunner`'s exception handling.
590
591An expected exception is specified with a traceback message. The
592lines between the first line and the type/value may be omitted or
593replaced with any other string:
594
595 >>> def f(x):
596 ... '''
597 ... >>> x = 12
598 ... >>> print x/0
599 ... Traceback (most recent call last):
600 ... ZeroDivisionError: integer division or modulo by zero
601 ... '''
602 >>> test = doctest.DocTestFinder().find(f)[0]
603 >>> doctest.DocTestRunner(verbose=False).run(test)
604 (0, 2)
605
606An example may generate output before it raises an exception; if it
607does, then the output must match the expected output:
608
609 >>> def f(x):
610 ... '''
611 ... >>> x = 12
612 ... >>> print 'pre-exception output', x/0
613 ... pre-exception output
614 ... Traceback (most recent call last):
615 ... ZeroDivisionError: integer division or modulo by zero
616 ... '''
617 >>> test = doctest.DocTestFinder().find(f)[0]
618 >>> doctest.DocTestRunner(verbose=False).run(test)
619 (0, 2)
620
621Exception messages may contain newlines:
622
623 >>> def f(x):
624 ... r'''
625 ... >>> raise ValueError, 'multi\nline\nmessage'
626 ... Traceback (most recent call last):
627 ... ValueError: multi
628 ... line
629 ... message
630 ... '''
631 >>> test = doctest.DocTestFinder().find(f)[0]
632 >>> doctest.DocTestRunner(verbose=False).run(test)
633 (0, 1)
634
635If an exception is expected, but an exception with the wrong type or
636message is raised, then it is reported as a failure:
637
638 >>> def f(x):
639 ... r'''
640 ... >>> raise ValueError, 'message'
641 ... Traceback (most recent call last):
642 ... ValueError: wrong message
643 ... '''
644 >>> test = doctest.DocTestFinder().find(f)[0]
645 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000646 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000647 **********************************************************************
648 Failure in example: raise ValueError, 'message'
649 from line #1 of f
650 Expected:
651 Traceback (most recent call last):
652 ValueError: wrong message
653 Got:
654 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000655 ...
Tim Peters8485b562004-08-04 18:46:34 +0000656 ValueError: message
657 (1, 1)
658
659If an exception is raised but not expected, then it is reported as an
660unexpected exception:
661
Tim Peters8485b562004-08-04 18:46:34 +0000662 >>> def f(x):
663 ... r'''
664 ... >>> 1/0
665 ... 0
666 ... '''
667 >>> test = doctest.DocTestFinder().find(f)[0]
668 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000669 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000670 **********************************************************************
671 Failure in example: 1/0
672 from line #1 of f
673 Exception raised:
674 Traceback (most recent call last):
675 ...
676 ZeroDivisionError: integer division or modulo by zero
677 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000678"""
679 def optionflags(): r"""
680Tests of `DocTestRunner`'s option flag handling.
681
682Several option flags can be used to customize the behavior of the test
683runner. These are defined as module constants in doctest, and passed
684to the DocTestRunner constructor (multiple constants should be or-ed
685together).
686
687The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
688and 1/0:
689
690 >>> def f(x):
691 ... '>>> True\n1\n'
692
693 >>> # Without the flag:
694 >>> test = doctest.DocTestFinder().find(f)[0]
695 >>> doctest.DocTestRunner(verbose=False).run(test)
696 (0, 1)
697
698 >>> # With the flag:
699 >>> test = doctest.DocTestFinder().find(f)[0]
700 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
701 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
702 **********************************************************************
703 Failure in example: True
704 from line #0 of f
705 Expected: 1
706 Got: True
707 (1, 1)
708
709The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
710and the '<BLANKLINE>' marker:
711
712 >>> def f(x):
713 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
714
715 >>> # Without the flag:
716 >>> test = doctest.DocTestFinder().find(f)[0]
717 >>> doctest.DocTestRunner(verbose=False).run(test)
718 (0, 1)
719
720 >>> # With the flag:
721 >>> test = doctest.DocTestFinder().find(f)[0]
722 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
723 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
724 **********************************************************************
725 Failure in example: print "a\n\nb"
726 from line #0 of f
727 Expected:
728 a
729 <BLANKLINE>
730 b
731 Got:
732 a
733 <BLANKLINE>
734 b
735 (1, 1)
736
737The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
738treated as equal:
739
740 >>> def f(x):
741 ... '>>> print 1, 2, 3\n 1 2\n 3'
742
743 >>> # Without the flag:
744 >>> test = doctest.DocTestFinder().find(f)[0]
745 >>> doctest.DocTestRunner(verbose=False).run(test)
746 **********************************************************************
747 Failure in example: print 1, 2, 3
748 from line #0 of f
749 Expected:
750 1 2
751 3
752 Got: 1 2 3
753 (1, 1)
754
755 >>> # With the flag:
756 >>> test = doctest.DocTestFinder().find(f)[0]
757 >>> flags = doctest.NORMALIZE_WHITESPACE
758 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
759 (0, 1)
760
Tim Peters026f8dc2004-08-19 16:38:58 +0000761 An example from the docs:
762 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
763 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
764 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
765
Tim Peters8485b562004-08-04 18:46:34 +0000766The ELLIPSIS flag causes ellipsis marker ("...") in the expected
767output to match any substring in the actual output:
768
769 >>> def f(x):
770 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
771
772 >>> # Without the flag:
773 >>> test = doctest.DocTestFinder().find(f)[0]
774 >>> doctest.DocTestRunner(verbose=False).run(test)
775 **********************************************************************
776 Failure in example: print range(15)
777 from line #0 of f
778 Expected: [0, 1, 2, ..., 14]
779 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
780 (1, 1)
781
782 >>> # With the flag:
783 >>> test = doctest.DocTestFinder().find(f)[0]
784 >>> flags = doctest.ELLIPSIS
785 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
786 (0, 1)
787
Tim Peterse594bee2004-08-22 01:47:51 +0000788 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +0000789
790 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +0000791 ... print i**2, #doctest: +ELLIPSIS
792 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +0000793
Tim Peters026f8dc2004-08-19 16:38:58 +0000794 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000795
796 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +0000797 ... print i,
798 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +0000799
Tim Peters026f8dc2004-08-19 16:38:58 +0000800 Examples from the docs:
801
802 >>> print range(20) # doctest:+ELLIPSIS
803 [0, 1, ..., 18, 19]
804
805 >>> print range(20) # doctest: +ELLIPSIS
806 ... # doctest: +NORMALIZE_WHITESPACE
807 [0, 1, ..., 18, 19]
808
Tim Peters8485b562004-08-04 18:46:34 +0000809The UNIFIED_DIFF flag causes failures that involve multi-line expected
810and actual outputs to be displayed using a unified diff:
811
812 >>> def f(x):
813 ... r'''
814 ... >>> print '\n'.join('abcdefg')
815 ... a
816 ... B
817 ... c
818 ... d
819 ... f
820 ... g
821 ... h
822 ... '''
823
824 >>> # Without the flag:
825 >>> test = doctest.DocTestFinder().find(f)[0]
826 >>> doctest.DocTestRunner(verbose=False).run(test)
827 **********************************************************************
828 Failure in example: print '\n'.join('abcdefg')
829 from line #1 of f
830 Expected:
831 a
832 B
833 c
834 d
835 f
836 g
837 h
838 Got:
839 a
840 b
841 c
842 d
843 e
844 f
845 g
846 (1, 1)
847
848 >>> # With the flag:
849 >>> test = doctest.DocTestFinder().find(f)[0]
850 >>> flags = doctest.UNIFIED_DIFF
851 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
852 **********************************************************************
853 Failure in example: print '\n'.join('abcdefg')
854 from line #1 of f
855 Differences (unified diff):
856 --- Expected
857 +++ Got
858 @@ -1,8 +1,8 @@
859 a
860 -B
861 +b
862 c
863 d
864 +e
865 f
866 g
867 -h
868 <BLANKLINE>
869 (1, 1)
870
871The CONTEXT_DIFF flag causes failures that involve multi-line expected
872and actual outputs to be displayed using a context diff:
873
874 >>> # Reuse f() from the UNIFIED_DIFF example, above.
875 >>> test = doctest.DocTestFinder().find(f)[0]
876 >>> flags = doctest.CONTEXT_DIFF
877 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
878 **********************************************************************
879 Failure in example: print '\n'.join('abcdefg')
880 from line #1 of f
881 Differences (context diff):
882 *** Expected
883 --- Got
884 ***************
885 *** 1,8 ****
886 a
887 ! B
888 c
889 d
890 f
891 g
892 - h
893 <BLANKLINE>
894 --- 1,8 ----
895 a
896 ! b
897 c
898 d
899 + e
900 f
901 g
902 <BLANKLINE>
903 (1, 1)
904"""
905 def option_directives(): r"""
906Tests of `DocTestRunner`'s option directive mechanism.
907
Edward Loper74bca7a2004-08-12 02:27:44 +0000908Option directives can be used to turn option flags on or off for a
909single example. To turn an option on for an example, follow that
910example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +0000911
912 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +0000913 ... >>> print range(10) # should fail: no ellipsis
914 ... [0, 1, ..., 9]
915 ...
916 ... >>> print range(10) # doctest: +ELLIPSIS
917 ... [0, 1, ..., 9]
918 ... '''
919 >>> test = doctest.DocTestFinder().find(f)[0]
920 >>> doctest.DocTestRunner(verbose=False).run(test)
921 **********************************************************************
922 Failure in example: print range(10) # should fail: no ellipsis
923 from line #1 of f
924 Expected: [0, 1, ..., 9]
925 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
926 (1, 2)
927
928To turn an option off for an example, follow that example with a
929comment of the form ``# doctest: -OPTION``:
930
931 >>> def f(x): r'''
932 ... >>> print range(10)
933 ... [0, 1, ..., 9]
934 ...
935 ... >>> # should fail: no ellipsis
936 ... >>> print range(10) # doctest: -ELLIPSIS
937 ... [0, 1, ..., 9]
938 ... '''
939 >>> test = doctest.DocTestFinder().find(f)[0]
940 >>> doctest.DocTestRunner(verbose=False,
941 ... optionflags=doctest.ELLIPSIS).run(test)
942 **********************************************************************
943 Failure in example: print range(10) # doctest: -ELLIPSIS
Edward Loperb51b2342004-08-17 16:37:12 +0000944 from line #5 of f
Edward Loper74bca7a2004-08-12 02:27:44 +0000945 Expected: [0, 1, ..., 9]
946 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
947 (1, 2)
948
949Option directives affect only the example that they appear with; they
950do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +0000951
Edward Loper74bca7a2004-08-12 02:27:44 +0000952 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +0000953 ... >>> print range(10) # Should fail: no ellipsis
954 ... [0, 1, ..., 9]
955 ...
Edward Loper74bca7a2004-08-12 02:27:44 +0000956 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000957 ... [0, 1, ..., 9]
958 ...
Tim Peters8485b562004-08-04 18:46:34 +0000959 ... >>> print range(10) # Should fail: no ellipsis
960 ... [0, 1, ..., 9]
961 ... '''
962 >>> test = doctest.DocTestFinder().find(f)[0]
963 >>> doctest.DocTestRunner(verbose=False).run(test)
964 **********************************************************************
965 Failure in example: print range(10) # Should fail: no ellipsis
966 from line #1 of f
967 Expected: [0, 1, ..., 9]
968 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
969 **********************************************************************
970 Failure in example: print range(10) # Should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +0000971 from line #7 of f
Tim Peters8485b562004-08-04 18:46:34 +0000972 Expected: [0, 1, ..., 9]
973 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
974 (2, 3)
975
Edward Loper74bca7a2004-08-12 02:27:44 +0000976Multiple options may be modified by a single option directive. They
977may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +0000978
979 >>> def f(x): r'''
980 ... >>> print range(10) # Should fail
981 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +0000982 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +0000983 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +0000984 ... [0, 1, ..., 9]
985 ... '''
986 >>> test = doctest.DocTestFinder().find(f)[0]
987 >>> doctest.DocTestRunner(verbose=False).run(test)
988 **********************************************************************
989 Failure in example: print range(10) # Should fail
990 from line #1 of f
991 Expected: [0, 1, ..., 9]
992 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
993 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +0000994
995 >>> def f(x): r'''
996 ... >>> print range(10) # Should fail
997 ... [0, 1, ..., 9]
998 ... >>> print range(10) # Should succeed
999 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1000 ... [0, 1, ..., 9]
1001 ... '''
1002 >>> test = doctest.DocTestFinder().find(f)[0]
1003 >>> doctest.DocTestRunner(verbose=False).run(test)
1004 **********************************************************************
1005 Failure in example: print range(10) # Should fail
1006 from line #1 of f
1007 Expected: [0, 1, ..., 9]
1008 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1009 (1, 2)
1010
1011 >>> def f(x): r'''
1012 ... >>> print range(10) # Should fail
1013 ... [0, 1, ..., 9]
1014 ... >>> print range(10) # Should succeed
1015 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1016 ... [0, 1, ..., 9]
1017 ... '''
1018 >>> test = doctest.DocTestFinder().find(f)[0]
1019 >>> doctest.DocTestRunner(verbose=False).run(test)
1020 **********************************************************************
1021 Failure in example: print range(10) # Should fail
1022 from line #1 of f
1023 Expected: [0, 1, ..., 9]
1024 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1025 (1, 2)
1026
1027The option directive may be put on the line following the source, as
1028long as a continuation prompt is used:
1029
1030 >>> def f(x): r'''
1031 ... >>> print range(10)
1032 ... ... # doctest: +ELLIPSIS
1033 ... [0, 1, ..., 9]
1034 ... '''
1035 >>> test = doctest.DocTestFinder().find(f)[0]
1036 >>> doctest.DocTestRunner(verbose=False).run(test)
1037 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001038
Edward Loper74bca7a2004-08-12 02:27:44 +00001039For examples with multi-line source, the option directive may appear
1040at the end of any line:
1041
1042 >>> def f(x): r'''
1043 ... >>> for x in range(10): # doctest: +ELLIPSIS
1044 ... ... print x,
1045 ... 0 1 2 ... 9
1046 ...
1047 ... >>> for x in range(10):
1048 ... ... print x, # doctest: +ELLIPSIS
1049 ... 0 1 2 ... 9
1050 ... '''
1051 >>> test = doctest.DocTestFinder().find(f)[0]
1052 >>> doctest.DocTestRunner(verbose=False).run(test)
1053 (0, 2)
1054
1055If more than one line of an example with multi-line source has an
1056option directive, then they are combined:
1057
1058 >>> def f(x): r'''
1059 ... Should fail (option directive not on the last line):
1060 ... >>> for x in range(10): # doctest: +ELLIPSIS
1061 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1062 ... 0 1 2...9
1063 ... '''
1064 >>> test = doctest.DocTestFinder().find(f)[0]
1065 >>> doctest.DocTestRunner(verbose=False).run(test)
1066 (0, 1)
1067
1068It is an error to have a comment of the form ``# doctest:`` that is
1069*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1070``OPTION`` is an option that has been registered with
1071`register_option`:
1072
1073 >>> # Error: Option not registered
1074 >>> s = '>>> print 12 #doctest: +BADOPTION'
1075 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1076 Traceback (most recent call last):
1077 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1078
1079 >>> # Error: No + or - prefix
1080 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1081 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1082 Traceback (most recent call last):
1083 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1084
1085It is an error to use an option directive on a line that contains no
1086source:
1087
1088 >>> s = '>>> # doctest: +ELLIPSIS'
1089 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1090 Traceback (most recent call last):
1091 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 +00001092"""
1093
1094def test_testsource(): r"""
1095Unit tests for `testsource()`.
1096
1097The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001098test with that name in that module, and converts it to a script. The
1099example code is converted to regular Python code. The surrounding
1100words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001101
1102 >>> import test.test_doctest
1103 >>> name = 'test.test_doctest.sample_func'
1104 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001105 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001106 #
Tim Peters8485b562004-08-04 18:46:34 +00001107 print sample_func(22)
1108 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001109 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001110 #
Edward Lopera5db6002004-08-12 02:41:30 +00001111 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001112
1113 >>> name = 'test.test_doctest.SampleNewStyleClass'
1114 >>> print doctest.testsource(test.test_doctest, name)
1115 print '1\n2\n3'
1116 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001117 ## 1
1118 ## 2
1119 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001120
1121 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1122 >>> print doctest.testsource(test.test_doctest, name)
1123 print SampleClass.a_classmethod(10)
1124 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001125 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001126 print SampleClass(0).a_classmethod(10)
1127 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001128 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001129"""
1130
1131def test_debug(): r"""
1132
1133Create a docstring that we want to debug:
1134
1135 >>> s = '''
1136 ... >>> x = 12
1137 ... >>> print x
1138 ... 12
1139 ... '''
1140
1141Create some fake stdin input, to feed to the debugger:
1142
1143 >>> import tempfile
1144 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1145 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1146 >>> fake_stdin.seek(0)
1147 >>> real_stdin = sys.stdin
1148 >>> sys.stdin = fake_stdin
1149
1150Run the debugger on the docstring, and then restore sys.stdin.
1151
Tim Peters8485b562004-08-04 18:46:34 +00001152 >>> try:
1153 ... doctest.debug_src(s)
1154 ... finally:
1155 ... sys.stdin = real_stdin
1156 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001157 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001158 > <string>(1)?()
1159 (Pdb) 12
1160 --Return--
1161 > <string>(1)?()->None
1162 (Pdb) 12
1163 (Pdb)
1164
1165"""
1166
Jim Fulton356fd192004-08-09 11:34:47 +00001167def test_pdb_set_trace():
1168 r"""Using pdb.set_trace from a doctest
1169
Tim Peters413ced62004-08-09 15:43:47 +00001170 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001171 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001172 you use it. The doctest module changes sys.stdout so that it can
1173 capture program output. It also temporarily replaces pdb.set_trace
1174 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001175 see debugger output.
1176
1177 >>> doc = '''
1178 ... >>> x = 42
1179 ... >>> import pdb; pdb.set_trace()
1180 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001181 >>> parser = doctest.DocTestParser()
1182 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001183 >>> runner = doctest.DocTestRunner(verbose=False)
1184
1185 To demonstrate this, we'll create a fake standard input that
1186 captures our debugger input:
1187
1188 >>> import tempfile
1189 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1190 >>> fake_stdin.write('\n'.join([
1191 ... 'up', # up out of pdb.set_trace
1192 ... 'up', # up again to get out of our wrapper
1193 ... 'print x', # print data defined by the example
1194 ... 'continue', # stop debugging
1195 ... '']))
1196 >>> fake_stdin.seek(0)
1197 >>> real_stdin = sys.stdin
1198 >>> sys.stdin = fake_stdin
1199
Edward Loper74bca7a2004-08-12 02:27:44 +00001200 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001201 --Return--
1202 > ...set_trace()->None
1203 -> Pdb().set_trace()
1204 (Pdb) > ...set_trace()
1205 -> real_pdb_set_trace()
1206 (Pdb) > <string>(1)?()
1207 (Pdb) 42
1208 (Pdb) (0, 2)
1209
1210 >>> sys.stdin = real_stdin
1211 >>> fake_stdin.close()
1212
1213 You can also put pdb.set_trace in a function called from a test:
1214
1215 >>> def calls_set_trace():
1216 ... y=2
1217 ... import pdb; pdb.set_trace()
1218
1219 >>> doc = '''
1220 ... >>> x=1
1221 ... >>> calls_set_trace()
1222 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001223 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001224 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1225 >>> fake_stdin.write('\n'.join([
1226 ... 'up', # up out of pdb.set_trace
1227 ... 'up', # up again to get out of our wrapper
1228 ... 'print y', # print data defined in the function
1229 ... 'up', # out of function
1230 ... 'print x', # print data defined by the example
1231 ... 'continue', # stop debugging
1232 ... '']))
1233 >>> fake_stdin.seek(0)
1234 >>> real_stdin = sys.stdin
1235 >>> sys.stdin = fake_stdin
1236
Edward Loper74bca7a2004-08-12 02:27:44 +00001237 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001238 --Return--
1239 > ...set_trace()->None
1240 -> Pdb().set_trace()
1241 (Pdb) ...set_trace()
1242 -> real_pdb_set_trace()
1243 (Pdb) > <string>(3)calls_set_trace()
1244 (Pdb) 2
1245 (Pdb) > <string>(1)?()
1246 (Pdb) 1
1247 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001248 """
1249
Tim Peters19397e52004-08-06 22:02:59 +00001250def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001251 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001252
1253 We create a Suite by providing a module. A module can be provided
1254 by passing a module object:
1255
1256 >>> import unittest
1257 >>> import test.sample_doctest
1258 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1259 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001260 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001261
1262 We can also supply the module by name:
1263
1264 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1265 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001266 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001267
1268 We can use the current module:
1269
1270 >>> suite = test.sample_doctest.test_suite()
1271 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001272 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001273
1274 We can supply global variables. If we pass globs, they will be
1275 used instead of the module globals. Here we'll pass an empty
1276 globals, triggering an extra error:
1277
1278 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1279 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001280 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001281
1282 Alternatively, we can provide extra globals. Here we'll make an
1283 error go away by providing an extra global variable:
1284
1285 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1286 ... extraglobs={'y': 1})
1287 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001288 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001289
1290 You can pass option flags. Here we'll cause an extra error
1291 by disabling the blank-line feature:
1292
1293 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001294 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001295 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001296 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001297
Tim Peters1e277ee2004-08-07 05:37:52 +00001298 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001299
1300 >>> def setUp():
1301 ... import test.test_doctest
1302 ... test.test_doctest.sillySetup = True
1303
1304 >>> def tearDown():
1305 ... import test.test_doctest
1306 ... del test.test_doctest.sillySetup
1307
1308 Here, we installed a silly variable that the test expects:
1309
1310 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1311 ... setUp=setUp, tearDown=tearDown)
1312 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001313 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001314
1315 But the tearDown restores sanity:
1316
1317 >>> import test.test_doctest
1318 >>> test.test_doctest.sillySetup
1319 Traceback (most recent call last):
1320 ...
1321 AttributeError: 'module' object has no attribute 'sillySetup'
1322
1323 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001324 use a custom test_finder to to run just the test named bar.
1325 However, the test in the module docstring, and the two tests
1326 in the module __test__ dict, aren't filtered, so we actually
1327 run three tests besides bar's. The filtering mechanisms are
1328 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001329
1330 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001331 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001332 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1333 ... test_finder=finder)
1334 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001335 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001336 """
1337
1338def test_DocFileSuite():
1339 """We can test tests found in text files using a DocFileSuite.
1340
1341 We create a suite by providing the names of one or more text
1342 files that include examples:
1343
1344 >>> import unittest
1345 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1346 ... 'test_doctest2.txt')
1347 >>> suite.run(unittest.TestResult())
1348 <unittest.TestResult run=2 errors=0 failures=2>
1349
1350 The test files are looked for in the directory containing the
1351 calling module. A package keyword argument can be provided to
1352 specify a different relative location.
1353
1354 >>> import unittest
1355 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1356 ... 'test_doctest2.txt',
1357 ... package='test')
1358 >>> suite.run(unittest.TestResult())
1359 <unittest.TestResult run=2 errors=0 failures=2>
1360
1361 Note that '/' should be used as a path separator. It will be
1362 converted to a native separator at run time:
1363
1364
1365 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1366 >>> suite.run(unittest.TestResult())
1367 <unittest.TestResult run=1 errors=0 failures=1>
1368
1369 You can specify initial global variables:
1370
1371 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1372 ... 'test_doctest2.txt',
1373 ... globs={'favorite_color': 'blue'})
1374 >>> suite.run(unittest.TestResult())
1375 <unittest.TestResult run=2 errors=0 failures=1>
1376
1377 In this case, we supplied a missing favorite color. You can
1378 provide doctest options:
1379
1380 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1381 ... 'test_doctest2.txt',
1382 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1383 ... globs={'favorite_color': 'blue'})
1384 >>> suite.run(unittest.TestResult())
1385 <unittest.TestResult run=2 errors=0 failures=2>
1386
1387 And, you can provide setUp and tearDown functions:
1388
1389 You can supply setUp and teatDoen functions:
1390
1391 >>> def setUp():
1392 ... import test.test_doctest
1393 ... test.test_doctest.sillySetup = True
1394
1395 >>> def tearDown():
1396 ... import test.test_doctest
1397 ... del test.test_doctest.sillySetup
1398
1399 Here, we installed a silly variable that the test expects:
1400
1401 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1402 ... 'test_doctest2.txt',
1403 ... setUp=setUp, tearDown=tearDown)
1404 >>> suite.run(unittest.TestResult())
1405 <unittest.TestResult run=2 errors=0 failures=1>
1406
1407 But the tearDown restores sanity:
1408
1409 >>> import test.test_doctest
1410 >>> test.test_doctest.sillySetup
1411 Traceback (most recent call last):
1412 ...
1413 AttributeError: 'module' object has no attribute 'sillySetup'
1414
1415 """
1416
1417
Tim Peters8485b562004-08-04 18:46:34 +00001418######################################################################
1419## Main
1420######################################################################
1421
1422def test_main():
1423 # Check the doctest cases in doctest itself:
1424 test_support.run_doctest(doctest, verbosity=True)
1425 # Check the doctest cases defined here:
1426 from test import test_doctest
1427 test_support.run_doctest(test_doctest, verbosity=True)
1428
1429import trace, sys, re, StringIO
1430def test_coverage(coverdir):
1431 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1432 trace=0, count=1)
1433 tracer.run('reload(doctest); test_main()')
1434 r = tracer.results()
1435 print 'Writing coverage results...'
1436 r.write_results(show_missing=True, summary=True,
1437 coverdir=coverdir)
1438
1439if __name__ == '__main__':
1440 if '-c' in sys.argv:
1441 test_coverage('/tmp/doctest.cover')
1442 else:
1443 test_main()