blob: 245a9f420f8dc19334c1e4c01f3479fe7819c3b3 [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 Peters026f8dc2004-08-19 16:38:58 +0000788 ... should also match nothing gracefully (note that a regular-expression
789 implementation of ELLIPSIS would take a loooong time to match this one!):
Tim Peters1cf3aa62004-08-19 06:49:33 +0000790
791 >>> for i in range(100):
792 ... print i**2 #doctest: +ELLIPSIS
793 0
794 ...
795 1
796 ...
Tim Peters26b3ebb2004-08-19 08:10:08 +0000797 ......
798 ...
Tim Peters1cf3aa62004-08-19 06:49:33 +0000799 36
800 ...
801 ...
Tim Peters26b3ebb2004-08-19 08:10:08 +0000802 ...
Tim Peters1cf3aa62004-08-19 06:49:33 +0000803 49
804 64
Tim Peters26b3ebb2004-08-19 08:10:08 +0000805 .........
Tim Peters1cf3aa62004-08-19 06:49:33 +0000806 9801
807 ...
808
Tim Peters026f8dc2004-08-19 16:38:58 +0000809 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000810
811 >>> for i in range(21): #doctest: +ELLIPSIS
812 ... print i
813 0
814 1
815 2
816 ...
817 1
818 ...
819 2
820 ...
821 0
822
Tim Peters026f8dc2004-08-19 16:38:58 +0000823 Examples from the docs:
824
825 >>> print range(20) # doctest:+ELLIPSIS
826 [0, 1, ..., 18, 19]
827
828 >>> print range(20) # doctest: +ELLIPSIS
829 ... # doctest: +NORMALIZE_WHITESPACE
830 [0, 1, ..., 18, 19]
831
Tim Peters8485b562004-08-04 18:46:34 +0000832The UNIFIED_DIFF flag causes failures that involve multi-line expected
833and actual outputs to be displayed using a unified diff:
834
835 >>> def f(x):
836 ... r'''
837 ... >>> print '\n'.join('abcdefg')
838 ... a
839 ... B
840 ... c
841 ... d
842 ... f
843 ... g
844 ... h
845 ... '''
846
847 >>> # Without the flag:
848 >>> test = doctest.DocTestFinder().find(f)[0]
849 >>> doctest.DocTestRunner(verbose=False).run(test)
850 **********************************************************************
851 Failure in example: print '\n'.join('abcdefg')
852 from line #1 of f
853 Expected:
854 a
855 B
856 c
857 d
858 f
859 g
860 h
861 Got:
862 a
863 b
864 c
865 d
866 e
867 f
868 g
869 (1, 1)
870
871 >>> # With the flag:
872 >>> test = doctest.DocTestFinder().find(f)[0]
873 >>> flags = doctest.UNIFIED_DIFF
874 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
875 **********************************************************************
876 Failure in example: print '\n'.join('abcdefg')
877 from line #1 of f
878 Differences (unified diff):
879 --- Expected
880 +++ Got
881 @@ -1,8 +1,8 @@
882 a
883 -B
884 +b
885 c
886 d
887 +e
888 f
889 g
890 -h
891 <BLANKLINE>
892 (1, 1)
893
894The CONTEXT_DIFF flag causes failures that involve multi-line expected
895and actual outputs to be displayed using a context diff:
896
897 >>> # Reuse f() from the UNIFIED_DIFF example, above.
898 >>> test = doctest.DocTestFinder().find(f)[0]
899 >>> flags = doctest.CONTEXT_DIFF
900 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
901 **********************************************************************
902 Failure in example: print '\n'.join('abcdefg')
903 from line #1 of f
904 Differences (context diff):
905 *** Expected
906 --- Got
907 ***************
908 *** 1,8 ****
909 a
910 ! B
911 c
912 d
913 f
914 g
915 - h
916 <BLANKLINE>
917 --- 1,8 ----
918 a
919 ! b
920 c
921 d
922 + e
923 f
924 g
925 <BLANKLINE>
926 (1, 1)
927"""
928 def option_directives(): r"""
929Tests of `DocTestRunner`'s option directive mechanism.
930
Edward Loper74bca7a2004-08-12 02:27:44 +0000931Option directives can be used to turn option flags on or off for a
932single example. To turn an option on for an example, follow that
933example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +0000934
935 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +0000936 ... >>> print range(10) # should fail: no ellipsis
937 ... [0, 1, ..., 9]
938 ...
939 ... >>> print range(10) # doctest: +ELLIPSIS
940 ... [0, 1, ..., 9]
941 ... '''
942 >>> test = doctest.DocTestFinder().find(f)[0]
943 >>> doctest.DocTestRunner(verbose=False).run(test)
944 **********************************************************************
945 Failure in example: print range(10) # should fail: no ellipsis
946 from line #1 of f
947 Expected: [0, 1, ..., 9]
948 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
949 (1, 2)
950
951To turn an option off for an example, follow that example with a
952comment of the form ``# doctest: -OPTION``:
953
954 >>> def f(x): r'''
955 ... >>> print range(10)
956 ... [0, 1, ..., 9]
957 ...
958 ... >>> # should fail: no ellipsis
959 ... >>> print range(10) # doctest: -ELLIPSIS
960 ... [0, 1, ..., 9]
961 ... '''
962 >>> test = doctest.DocTestFinder().find(f)[0]
963 >>> doctest.DocTestRunner(verbose=False,
964 ... optionflags=doctest.ELLIPSIS).run(test)
965 **********************************************************************
966 Failure in example: print range(10) # doctest: -ELLIPSIS
Edward Loperb51b2342004-08-17 16:37:12 +0000967 from line #5 of f
Edward Loper74bca7a2004-08-12 02:27:44 +0000968 Expected: [0, 1, ..., 9]
969 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
970 (1, 2)
971
972Option directives affect only the example that they appear with; they
973do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +0000974
Edward Loper74bca7a2004-08-12 02:27:44 +0000975 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +0000976 ... >>> print range(10) # Should fail: no ellipsis
977 ... [0, 1, ..., 9]
978 ...
Edward Loper74bca7a2004-08-12 02:27:44 +0000979 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000980 ... [0, 1, ..., 9]
981 ...
Tim Peters8485b562004-08-04 18:46:34 +0000982 ... >>> print range(10) # Should fail: no ellipsis
983 ... [0, 1, ..., 9]
984 ... '''
985 >>> test = doctest.DocTestFinder().find(f)[0]
986 >>> doctest.DocTestRunner(verbose=False).run(test)
987 **********************************************************************
988 Failure in example: print range(10) # Should fail: no ellipsis
989 from line #1 of f
990 Expected: [0, 1, ..., 9]
991 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
992 **********************************************************************
993 Failure in example: print range(10) # Should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +0000994 from line #7 of f
Tim Peters8485b562004-08-04 18:46:34 +0000995 Expected: [0, 1, ..., 9]
996 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
997 (2, 3)
998
Edward Loper74bca7a2004-08-12 02:27:44 +0000999Multiple options may be modified by a single option directive. They
1000may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001001
1002 >>> def f(x): r'''
1003 ... >>> print range(10) # Should fail
1004 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001005 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001006 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001007 ... [0, 1, ..., 9]
1008 ... '''
1009 >>> test = doctest.DocTestFinder().find(f)[0]
1010 >>> doctest.DocTestRunner(verbose=False).run(test)
1011 **********************************************************************
1012 Failure in example: print range(10) # Should fail
1013 from line #1 of f
1014 Expected: [0, 1, ..., 9]
1015 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1016 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001017
1018 >>> def f(x): r'''
1019 ... >>> print range(10) # Should fail
1020 ... [0, 1, ..., 9]
1021 ... >>> print range(10) # Should succeed
1022 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1023 ... [0, 1, ..., 9]
1024 ... '''
1025 >>> test = doctest.DocTestFinder().find(f)[0]
1026 >>> doctest.DocTestRunner(verbose=False).run(test)
1027 **********************************************************************
1028 Failure in example: print range(10) # Should fail
1029 from line #1 of f
1030 Expected: [0, 1, ..., 9]
1031 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1032 (1, 2)
1033
1034 >>> def f(x): r'''
1035 ... >>> print range(10) # Should fail
1036 ... [0, 1, ..., 9]
1037 ... >>> print range(10) # Should succeed
1038 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1039 ... [0, 1, ..., 9]
1040 ... '''
1041 >>> test = doctest.DocTestFinder().find(f)[0]
1042 >>> doctest.DocTestRunner(verbose=False).run(test)
1043 **********************************************************************
1044 Failure in example: print range(10) # Should fail
1045 from line #1 of f
1046 Expected: [0, 1, ..., 9]
1047 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1048 (1, 2)
1049
1050The option directive may be put on the line following the source, as
1051long as a continuation prompt is used:
1052
1053 >>> def f(x): r'''
1054 ... >>> print range(10)
1055 ... ... # doctest: +ELLIPSIS
1056 ... [0, 1, ..., 9]
1057 ... '''
1058 >>> test = doctest.DocTestFinder().find(f)[0]
1059 >>> doctest.DocTestRunner(verbose=False).run(test)
1060 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001061
Edward Loper74bca7a2004-08-12 02:27:44 +00001062For examples with multi-line source, the option directive may appear
1063at the end of any line:
1064
1065 >>> def f(x): r'''
1066 ... >>> for x in range(10): # doctest: +ELLIPSIS
1067 ... ... print x,
1068 ... 0 1 2 ... 9
1069 ...
1070 ... >>> for x in range(10):
1071 ... ... print x, # doctest: +ELLIPSIS
1072 ... 0 1 2 ... 9
1073 ... '''
1074 >>> test = doctest.DocTestFinder().find(f)[0]
1075 >>> doctest.DocTestRunner(verbose=False).run(test)
1076 (0, 2)
1077
1078If more than one line of an example with multi-line source has an
1079option directive, then they are combined:
1080
1081 >>> def f(x): r'''
1082 ... Should fail (option directive not on the last line):
1083 ... >>> for x in range(10): # doctest: +ELLIPSIS
1084 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1085 ... 0 1 2...9
1086 ... '''
1087 >>> test = doctest.DocTestFinder().find(f)[0]
1088 >>> doctest.DocTestRunner(verbose=False).run(test)
1089 (0, 1)
1090
1091It is an error to have a comment of the form ``# doctest:`` that is
1092*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1093``OPTION`` is an option that has been registered with
1094`register_option`:
1095
1096 >>> # Error: Option not registered
1097 >>> s = '>>> print 12 #doctest: +BADOPTION'
1098 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1099 Traceback (most recent call last):
1100 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1101
1102 >>> # Error: No + or - prefix
1103 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1104 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1105 Traceback (most recent call last):
1106 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1107
1108It is an error to use an option directive on a line that contains no
1109source:
1110
1111 >>> s = '>>> # doctest: +ELLIPSIS'
1112 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1113 Traceback (most recent call last):
1114 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 +00001115"""
1116
1117def test_testsource(): r"""
1118Unit tests for `testsource()`.
1119
1120The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001121test with that name in that module, and converts it to a script. The
1122example code is converted to regular Python code. The surrounding
1123words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001124
1125 >>> import test.test_doctest
1126 >>> name = 'test.test_doctest.sample_func'
1127 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001128 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001129 #
Tim Peters8485b562004-08-04 18:46:34 +00001130 print sample_func(22)
1131 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001132 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001133 #
Edward Lopera5db6002004-08-12 02:41:30 +00001134 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001135
1136 >>> name = 'test.test_doctest.SampleNewStyleClass'
1137 >>> print doctest.testsource(test.test_doctest, name)
1138 print '1\n2\n3'
1139 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001140 ## 1
1141 ## 2
1142 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001143
1144 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1145 >>> print doctest.testsource(test.test_doctest, name)
1146 print SampleClass.a_classmethod(10)
1147 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001148 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001149 print SampleClass(0).a_classmethod(10)
1150 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001151 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001152"""
1153
1154def test_debug(): r"""
1155
1156Create a docstring that we want to debug:
1157
1158 >>> s = '''
1159 ... >>> x = 12
1160 ... >>> print x
1161 ... 12
1162 ... '''
1163
1164Create some fake stdin input, to feed to the debugger:
1165
1166 >>> import tempfile
1167 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1168 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1169 >>> fake_stdin.seek(0)
1170 >>> real_stdin = sys.stdin
1171 >>> sys.stdin = fake_stdin
1172
1173Run the debugger on the docstring, and then restore sys.stdin.
1174
Tim Peters8485b562004-08-04 18:46:34 +00001175 >>> try:
1176 ... doctest.debug_src(s)
1177 ... finally:
1178 ... sys.stdin = real_stdin
1179 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001180 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001181 > <string>(1)?()
1182 (Pdb) 12
1183 --Return--
1184 > <string>(1)?()->None
1185 (Pdb) 12
1186 (Pdb)
1187
1188"""
1189
Jim Fulton356fd192004-08-09 11:34:47 +00001190def test_pdb_set_trace():
1191 r"""Using pdb.set_trace from a doctest
1192
Tim Peters413ced62004-08-09 15:43:47 +00001193 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001194 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001195 you use it. The doctest module changes sys.stdout so that it can
1196 capture program output. It also temporarily replaces pdb.set_trace
1197 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001198 see debugger output.
1199
1200 >>> doc = '''
1201 ... >>> x = 42
1202 ... >>> import pdb; pdb.set_trace()
1203 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001204 >>> parser = doctest.DocTestParser()
1205 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001206 >>> runner = doctest.DocTestRunner(verbose=False)
1207
1208 To demonstrate this, we'll create a fake standard input that
1209 captures our debugger input:
1210
1211 >>> import tempfile
1212 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1213 >>> fake_stdin.write('\n'.join([
1214 ... 'up', # up out of pdb.set_trace
1215 ... 'up', # up again to get out of our wrapper
1216 ... 'print x', # print data defined by the example
1217 ... 'continue', # stop debugging
1218 ... '']))
1219 >>> fake_stdin.seek(0)
1220 >>> real_stdin = sys.stdin
1221 >>> sys.stdin = fake_stdin
1222
Edward Loper74bca7a2004-08-12 02:27:44 +00001223 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001224 --Return--
1225 > ...set_trace()->None
1226 -> Pdb().set_trace()
1227 (Pdb) > ...set_trace()
1228 -> real_pdb_set_trace()
1229 (Pdb) > <string>(1)?()
1230 (Pdb) 42
1231 (Pdb) (0, 2)
1232
1233 >>> sys.stdin = real_stdin
1234 >>> fake_stdin.close()
1235
1236 You can also put pdb.set_trace in a function called from a test:
1237
1238 >>> def calls_set_trace():
1239 ... y=2
1240 ... import pdb; pdb.set_trace()
1241
1242 >>> doc = '''
1243 ... >>> x=1
1244 ... >>> calls_set_trace()
1245 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001246 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001247 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1248 >>> fake_stdin.write('\n'.join([
1249 ... 'up', # up out of pdb.set_trace
1250 ... 'up', # up again to get out of our wrapper
1251 ... 'print y', # print data defined in the function
1252 ... 'up', # out of function
1253 ... 'print x', # print data defined by the example
1254 ... 'continue', # stop debugging
1255 ... '']))
1256 >>> fake_stdin.seek(0)
1257 >>> real_stdin = sys.stdin
1258 >>> sys.stdin = fake_stdin
1259
Edward Loper74bca7a2004-08-12 02:27:44 +00001260 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001261 --Return--
1262 > ...set_trace()->None
1263 -> Pdb().set_trace()
1264 (Pdb) ...set_trace()
1265 -> real_pdb_set_trace()
1266 (Pdb) > <string>(3)calls_set_trace()
1267 (Pdb) 2
1268 (Pdb) > <string>(1)?()
1269 (Pdb) 1
1270 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001271 """
1272
Tim Peters19397e52004-08-06 22:02:59 +00001273def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001274 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001275
1276 We create a Suite by providing a module. A module can be provided
1277 by passing a module object:
1278
1279 >>> import unittest
1280 >>> import test.sample_doctest
1281 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1282 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001283 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001284
1285 We can also supply the module by name:
1286
1287 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1288 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001289 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001290
1291 We can use the current module:
1292
1293 >>> suite = test.sample_doctest.test_suite()
1294 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001295 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001296
1297 We can supply global variables. If we pass globs, they will be
1298 used instead of the module globals. Here we'll pass an empty
1299 globals, triggering an extra error:
1300
1301 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1302 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001303 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001304
1305 Alternatively, we can provide extra globals. Here we'll make an
1306 error go away by providing an extra global variable:
1307
1308 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1309 ... extraglobs={'y': 1})
1310 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001311 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001312
1313 You can pass option flags. Here we'll cause an extra error
1314 by disabling the blank-line feature:
1315
1316 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001317 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001318 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001319 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001320
Tim Peters1e277ee2004-08-07 05:37:52 +00001321 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001322
1323 >>> def setUp():
1324 ... import test.test_doctest
1325 ... test.test_doctest.sillySetup = True
1326
1327 >>> def tearDown():
1328 ... import test.test_doctest
1329 ... del test.test_doctest.sillySetup
1330
1331 Here, we installed a silly variable that the test expects:
1332
1333 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1334 ... setUp=setUp, tearDown=tearDown)
1335 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001336 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001337
1338 But the tearDown restores sanity:
1339
1340 >>> import test.test_doctest
1341 >>> test.test_doctest.sillySetup
1342 Traceback (most recent call last):
1343 ...
1344 AttributeError: 'module' object has no attribute 'sillySetup'
1345
1346 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001347 use a custom test_finder to to run just the test named bar.
1348 However, the test in the module docstring, and the two tests
1349 in the module __test__ dict, aren't filtered, so we actually
1350 run three tests besides bar's. The filtering mechanisms are
1351 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001352
1353 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001354 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001355 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1356 ... test_finder=finder)
1357 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001358 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001359 """
1360
1361def test_DocFileSuite():
1362 """We can test tests found in text files using a DocFileSuite.
1363
1364 We create a suite by providing the names of one or more text
1365 files that include examples:
1366
1367 >>> import unittest
1368 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1369 ... 'test_doctest2.txt')
1370 >>> suite.run(unittest.TestResult())
1371 <unittest.TestResult run=2 errors=0 failures=2>
1372
1373 The test files are looked for in the directory containing the
1374 calling module. A package keyword argument can be provided to
1375 specify a different relative location.
1376
1377 >>> import unittest
1378 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1379 ... 'test_doctest2.txt',
1380 ... package='test')
1381 >>> suite.run(unittest.TestResult())
1382 <unittest.TestResult run=2 errors=0 failures=2>
1383
1384 Note that '/' should be used as a path separator. It will be
1385 converted to a native separator at run time:
1386
1387
1388 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1389 >>> suite.run(unittest.TestResult())
1390 <unittest.TestResult run=1 errors=0 failures=1>
1391
1392 You can specify initial global variables:
1393
1394 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1395 ... 'test_doctest2.txt',
1396 ... globs={'favorite_color': 'blue'})
1397 >>> suite.run(unittest.TestResult())
1398 <unittest.TestResult run=2 errors=0 failures=1>
1399
1400 In this case, we supplied a missing favorite color. You can
1401 provide doctest options:
1402
1403 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1404 ... 'test_doctest2.txt',
1405 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1406 ... globs={'favorite_color': 'blue'})
1407 >>> suite.run(unittest.TestResult())
1408 <unittest.TestResult run=2 errors=0 failures=2>
1409
1410 And, you can provide setUp and tearDown functions:
1411
1412 You can supply setUp and teatDoen functions:
1413
1414 >>> def setUp():
1415 ... import test.test_doctest
1416 ... test.test_doctest.sillySetup = True
1417
1418 >>> def tearDown():
1419 ... import test.test_doctest
1420 ... del test.test_doctest.sillySetup
1421
1422 Here, we installed a silly variable that the test expects:
1423
1424 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1425 ... 'test_doctest2.txt',
1426 ... setUp=setUp, tearDown=tearDown)
1427 >>> suite.run(unittest.TestResult())
1428 <unittest.TestResult run=2 errors=0 failures=1>
1429
1430 But the tearDown restores sanity:
1431
1432 >>> import test.test_doctest
1433 >>> test.test_doctest.sillySetup
1434 Traceback (most recent call last):
1435 ...
1436 AttributeError: 'module' object has no attribute 'sillySetup'
1437
1438 """
1439
1440
Tim Peters8485b562004-08-04 18:46:34 +00001441######################################################################
1442## Main
1443######################################################################
1444
1445def test_main():
1446 # Check the doctest cases in doctest itself:
1447 test_support.run_doctest(doctest, verbosity=True)
1448 # Check the doctest cases defined here:
1449 from test import test_doctest
1450 test_support.run_doctest(test_doctest, verbosity=True)
1451
1452import trace, sys, re, StringIO
1453def test_coverage(coverdir):
1454 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1455 trace=0, count=1)
1456 tracer.run('reload(doctest); test_main()')
1457 r = tracer.results()
1458 print 'Writing coverage results...'
1459 r.write_results(show_missing=True, summary=True,
1460 coverdir=coverdir)
1461
1462if __name__ == '__main__':
1463 if '-c' in sys.argv:
1464 test_coverage('/tmp/doctest.cover')
1465 else:
1466 test_main()