blob: d49e6cff0cb67046e40e5607cdfe9a4bb38997d6 [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
761The ELLIPSIS flag causes ellipsis marker ("...") in the expected
762output to match any substring in the actual output:
763
764 >>> def f(x):
765 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
766
767 >>> # Without the flag:
768 >>> test = doctest.DocTestFinder().find(f)[0]
769 >>> doctest.DocTestRunner(verbose=False).run(test)
770 **********************************************************************
771 Failure in example: print range(15)
772 from line #0 of f
773 Expected: [0, 1, 2, ..., 14]
774 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
775 (1, 1)
776
777 >>> # With the flag:
778 >>> test = doctest.DocTestFinder().find(f)[0]
779 >>> flags = doctest.ELLIPSIS
780 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
781 (0, 1)
782
Tim Peters1cf3aa62004-08-19 06:49:33 +0000783... should also match nothing gracefully:
784XXX This can be provoked into requiring exponential time by adding more
785XXX ellipses; the implementation should change. It's much easier to
786XXX provoke exponential time with expected output that doesn't match,
787XXX BTW (then multiple regexp .* thingies each try all possiblities,
788XXX multiplicatively, without hope of success). That's the real danger,
789XXX that a failing test will appear to be hung.
790
791 >>> for i in range(100):
792 ... print i**2 #doctest: +ELLIPSIS
793 0
794 ...
795 1
796 ...
797 36
798 ...
799 ...
800 49
801 64
802 ......
803 9801
804 ...
805
Tim Peters8485b562004-08-04 18:46:34 +0000806The UNIFIED_DIFF flag causes failures that involve multi-line expected
807and actual outputs to be displayed using a unified diff:
808
809 >>> def f(x):
810 ... r'''
811 ... >>> print '\n'.join('abcdefg')
812 ... a
813 ... B
814 ... c
815 ... d
816 ... f
817 ... g
818 ... h
819 ... '''
820
821 >>> # Without the flag:
822 >>> test = doctest.DocTestFinder().find(f)[0]
823 >>> doctest.DocTestRunner(verbose=False).run(test)
824 **********************************************************************
825 Failure in example: print '\n'.join('abcdefg')
826 from line #1 of f
827 Expected:
828 a
829 B
830 c
831 d
832 f
833 g
834 h
835 Got:
836 a
837 b
838 c
839 d
840 e
841 f
842 g
843 (1, 1)
844
845 >>> # With the flag:
846 >>> test = doctest.DocTestFinder().find(f)[0]
847 >>> flags = doctest.UNIFIED_DIFF
848 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
849 **********************************************************************
850 Failure in example: print '\n'.join('abcdefg')
851 from line #1 of f
852 Differences (unified diff):
853 --- Expected
854 +++ Got
855 @@ -1,8 +1,8 @@
856 a
857 -B
858 +b
859 c
860 d
861 +e
862 f
863 g
864 -h
865 <BLANKLINE>
866 (1, 1)
867
868The CONTEXT_DIFF flag causes failures that involve multi-line expected
869and actual outputs to be displayed using a context diff:
870
871 >>> # Reuse f() from the UNIFIED_DIFF example, above.
872 >>> test = doctest.DocTestFinder().find(f)[0]
873 >>> flags = doctest.CONTEXT_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 (context diff):
879 *** Expected
880 --- Got
881 ***************
882 *** 1,8 ****
883 a
884 ! B
885 c
886 d
887 f
888 g
889 - h
890 <BLANKLINE>
891 --- 1,8 ----
892 a
893 ! b
894 c
895 d
896 + e
897 f
898 g
899 <BLANKLINE>
900 (1, 1)
901"""
902 def option_directives(): r"""
903Tests of `DocTestRunner`'s option directive mechanism.
904
Edward Loper74bca7a2004-08-12 02:27:44 +0000905Option directives can be used to turn option flags on or off for a
906single example. To turn an option on for an example, follow that
907example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +0000908
909 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +0000910 ... >>> print range(10) # should fail: no ellipsis
911 ... [0, 1, ..., 9]
912 ...
913 ... >>> print range(10) # doctest: +ELLIPSIS
914 ... [0, 1, ..., 9]
915 ... '''
916 >>> test = doctest.DocTestFinder().find(f)[0]
917 >>> doctest.DocTestRunner(verbose=False).run(test)
918 **********************************************************************
919 Failure in example: print range(10) # should fail: no ellipsis
920 from line #1 of f
921 Expected: [0, 1, ..., 9]
922 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
923 (1, 2)
924
925To turn an option off for an example, follow that example with a
926comment of the form ``# doctest: -OPTION``:
927
928 >>> def f(x): r'''
929 ... >>> print range(10)
930 ... [0, 1, ..., 9]
931 ...
932 ... >>> # should fail: no ellipsis
933 ... >>> print range(10) # doctest: -ELLIPSIS
934 ... [0, 1, ..., 9]
935 ... '''
936 >>> test = doctest.DocTestFinder().find(f)[0]
937 >>> doctest.DocTestRunner(verbose=False,
938 ... optionflags=doctest.ELLIPSIS).run(test)
939 **********************************************************************
940 Failure in example: print range(10) # doctest: -ELLIPSIS
Edward Loperb51b2342004-08-17 16:37:12 +0000941 from line #5 of f
Edward Loper74bca7a2004-08-12 02:27:44 +0000942 Expected: [0, 1, ..., 9]
943 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
944 (1, 2)
945
946Option directives affect only the example that they appear with; they
947do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +0000948
Edward Loper74bca7a2004-08-12 02:27:44 +0000949 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +0000950 ... >>> print range(10) # Should fail: no ellipsis
951 ... [0, 1, ..., 9]
952 ...
Edward Loper74bca7a2004-08-12 02:27:44 +0000953 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000954 ... [0, 1, ..., 9]
955 ...
Tim Peters8485b562004-08-04 18:46:34 +0000956 ... >>> print range(10) # Should fail: no ellipsis
957 ... [0, 1, ..., 9]
958 ... '''
959 >>> test = doctest.DocTestFinder().find(f)[0]
960 >>> doctest.DocTestRunner(verbose=False).run(test)
961 **********************************************************************
962 Failure in example: print range(10) # Should fail: no ellipsis
963 from line #1 of f
964 Expected: [0, 1, ..., 9]
965 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
966 **********************************************************************
967 Failure in example: print range(10) # Should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +0000968 from line #7 of f
Tim Peters8485b562004-08-04 18:46:34 +0000969 Expected: [0, 1, ..., 9]
970 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
971 (2, 3)
972
Edward Loper74bca7a2004-08-12 02:27:44 +0000973Multiple options may be modified by a single option directive. They
974may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +0000975
976 >>> def f(x): r'''
977 ... >>> print range(10) # Should fail
978 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +0000979 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +0000980 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +0000981 ... [0, 1, ..., 9]
982 ... '''
983 >>> test = doctest.DocTestFinder().find(f)[0]
984 >>> doctest.DocTestRunner(verbose=False).run(test)
985 **********************************************************************
986 Failure in example: print range(10) # Should fail
987 from line #1 of f
988 Expected: [0, 1, ..., 9]
989 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
990 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +0000991
992 >>> def f(x): r'''
993 ... >>> print range(10) # Should fail
994 ... [0, 1, ..., 9]
995 ... >>> print range(10) # Should succeed
996 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
997 ... [0, 1, ..., 9]
998 ... '''
999 >>> test = doctest.DocTestFinder().find(f)[0]
1000 >>> doctest.DocTestRunner(verbose=False).run(test)
1001 **********************************************************************
1002 Failure in example: print range(10) # Should fail
1003 from line #1 of f
1004 Expected: [0, 1, ..., 9]
1005 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1006 (1, 2)
1007
1008 >>> def f(x): r'''
1009 ... >>> print range(10) # Should fail
1010 ... [0, 1, ..., 9]
1011 ... >>> print range(10) # Should succeed
1012 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1013 ... [0, 1, ..., 9]
1014 ... '''
1015 >>> test = doctest.DocTestFinder().find(f)[0]
1016 >>> doctest.DocTestRunner(verbose=False).run(test)
1017 **********************************************************************
1018 Failure in example: print range(10) # Should fail
1019 from line #1 of f
1020 Expected: [0, 1, ..., 9]
1021 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1022 (1, 2)
1023
1024The option directive may be put on the line following the source, as
1025long as a continuation prompt is used:
1026
1027 >>> def f(x): r'''
1028 ... >>> print range(10)
1029 ... ... # doctest: +ELLIPSIS
1030 ... [0, 1, ..., 9]
1031 ... '''
1032 >>> test = doctest.DocTestFinder().find(f)[0]
1033 >>> doctest.DocTestRunner(verbose=False).run(test)
1034 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001035
Edward Loper74bca7a2004-08-12 02:27:44 +00001036For examples with multi-line source, the option directive may appear
1037at the end of any line:
1038
1039 >>> def f(x): r'''
1040 ... >>> for x in range(10): # doctest: +ELLIPSIS
1041 ... ... print x,
1042 ... 0 1 2 ... 9
1043 ...
1044 ... >>> for x in range(10):
1045 ... ... print x, # doctest: +ELLIPSIS
1046 ... 0 1 2 ... 9
1047 ... '''
1048 >>> test = doctest.DocTestFinder().find(f)[0]
1049 >>> doctest.DocTestRunner(verbose=False).run(test)
1050 (0, 2)
1051
1052If more than one line of an example with multi-line source has an
1053option directive, then they are combined:
1054
1055 >>> def f(x): r'''
1056 ... Should fail (option directive not on the last line):
1057 ... >>> for x in range(10): # doctest: +ELLIPSIS
1058 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1059 ... 0 1 2...9
1060 ... '''
1061 >>> test = doctest.DocTestFinder().find(f)[0]
1062 >>> doctest.DocTestRunner(verbose=False).run(test)
1063 (0, 1)
1064
1065It is an error to have a comment of the form ``# doctest:`` that is
1066*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1067``OPTION`` is an option that has been registered with
1068`register_option`:
1069
1070 >>> # Error: Option not registered
1071 >>> s = '>>> print 12 #doctest: +BADOPTION'
1072 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1073 Traceback (most recent call last):
1074 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1075
1076 >>> # Error: No + or - prefix
1077 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1078 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1079 Traceback (most recent call last):
1080 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1081
1082It is an error to use an option directive on a line that contains no
1083source:
1084
1085 >>> s = '>>> # doctest: +ELLIPSIS'
1086 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1087 Traceback (most recent call last):
1088 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 +00001089"""
1090
1091def test_testsource(): r"""
1092Unit tests for `testsource()`.
1093
1094The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001095test with that name in that module, and converts it to a script. The
1096example code is converted to regular Python code. The surrounding
1097words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001098
1099 >>> import test.test_doctest
1100 >>> name = 'test.test_doctest.sample_func'
1101 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001102 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001103 #
Tim Peters8485b562004-08-04 18:46:34 +00001104 print sample_func(22)
1105 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001106 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001107 #
Edward Lopera5db6002004-08-12 02:41:30 +00001108 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001109
1110 >>> name = 'test.test_doctest.SampleNewStyleClass'
1111 >>> print doctest.testsource(test.test_doctest, name)
1112 print '1\n2\n3'
1113 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001114 ## 1
1115 ## 2
1116 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001117
1118 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1119 >>> print doctest.testsource(test.test_doctest, name)
1120 print SampleClass.a_classmethod(10)
1121 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001122 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001123 print SampleClass(0).a_classmethod(10)
1124 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001125 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001126"""
1127
1128def test_debug(): r"""
1129
1130Create a docstring that we want to debug:
1131
1132 >>> s = '''
1133 ... >>> x = 12
1134 ... >>> print x
1135 ... 12
1136 ... '''
1137
1138Create some fake stdin input, to feed to the debugger:
1139
1140 >>> import tempfile
1141 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1142 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1143 >>> fake_stdin.seek(0)
1144 >>> real_stdin = sys.stdin
1145 >>> sys.stdin = fake_stdin
1146
1147Run the debugger on the docstring, and then restore sys.stdin.
1148
Tim Peters8485b562004-08-04 18:46:34 +00001149 >>> try:
1150 ... doctest.debug_src(s)
1151 ... finally:
1152 ... sys.stdin = real_stdin
1153 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001154 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001155 > <string>(1)?()
1156 (Pdb) 12
1157 --Return--
1158 > <string>(1)?()->None
1159 (Pdb) 12
1160 (Pdb)
1161
1162"""
1163
Jim Fulton356fd192004-08-09 11:34:47 +00001164def test_pdb_set_trace():
1165 r"""Using pdb.set_trace from a doctest
1166
Tim Peters413ced62004-08-09 15:43:47 +00001167 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001168 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001169 you use it. The doctest module changes sys.stdout so that it can
1170 capture program output. It also temporarily replaces pdb.set_trace
1171 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001172 see debugger output.
1173
1174 >>> doc = '''
1175 ... >>> x = 42
1176 ... >>> import pdb; pdb.set_trace()
1177 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001178 >>> parser = doctest.DocTestParser()
1179 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001180 >>> runner = doctest.DocTestRunner(verbose=False)
1181
1182 To demonstrate this, we'll create a fake standard input that
1183 captures our debugger input:
1184
1185 >>> import tempfile
1186 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1187 >>> fake_stdin.write('\n'.join([
1188 ... 'up', # up out of pdb.set_trace
1189 ... 'up', # up again to get out of our wrapper
1190 ... 'print x', # print data defined by the example
1191 ... 'continue', # stop debugging
1192 ... '']))
1193 >>> fake_stdin.seek(0)
1194 >>> real_stdin = sys.stdin
1195 >>> sys.stdin = fake_stdin
1196
Edward Loper74bca7a2004-08-12 02:27:44 +00001197 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001198 --Return--
1199 > ...set_trace()->None
1200 -> Pdb().set_trace()
1201 (Pdb) > ...set_trace()
1202 -> real_pdb_set_trace()
1203 (Pdb) > <string>(1)?()
1204 (Pdb) 42
1205 (Pdb) (0, 2)
1206
1207 >>> sys.stdin = real_stdin
1208 >>> fake_stdin.close()
1209
1210 You can also put pdb.set_trace in a function called from a test:
1211
1212 >>> def calls_set_trace():
1213 ... y=2
1214 ... import pdb; pdb.set_trace()
1215
1216 >>> doc = '''
1217 ... >>> x=1
1218 ... >>> calls_set_trace()
1219 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001220 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001221 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1222 >>> fake_stdin.write('\n'.join([
1223 ... 'up', # up out of pdb.set_trace
1224 ... 'up', # up again to get out of our wrapper
1225 ... 'print y', # print data defined in the function
1226 ... 'up', # out of function
1227 ... 'print x', # print data defined by the example
1228 ... 'continue', # stop debugging
1229 ... '']))
1230 >>> fake_stdin.seek(0)
1231 >>> real_stdin = sys.stdin
1232 >>> sys.stdin = fake_stdin
1233
Edward Loper74bca7a2004-08-12 02:27:44 +00001234 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001235 --Return--
1236 > ...set_trace()->None
1237 -> Pdb().set_trace()
1238 (Pdb) ...set_trace()
1239 -> real_pdb_set_trace()
1240 (Pdb) > <string>(3)calls_set_trace()
1241 (Pdb) 2
1242 (Pdb) > <string>(1)?()
1243 (Pdb) 1
1244 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001245 """
1246
Tim Peters19397e52004-08-06 22:02:59 +00001247def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001248 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001249
1250 We create a Suite by providing a module. A module can be provided
1251 by passing a module object:
1252
1253 >>> import unittest
1254 >>> import test.sample_doctest
1255 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1256 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001257 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001258
1259 We can also supply the module by name:
1260
1261 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1262 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001263 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001264
1265 We can use the current module:
1266
1267 >>> suite = test.sample_doctest.test_suite()
1268 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001269 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001270
1271 We can supply global variables. If we pass globs, they will be
1272 used instead of the module globals. Here we'll pass an empty
1273 globals, triggering an extra error:
1274
1275 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1276 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001277 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001278
1279 Alternatively, we can provide extra globals. Here we'll make an
1280 error go away by providing an extra global variable:
1281
1282 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1283 ... extraglobs={'y': 1})
1284 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001285 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001286
1287 You can pass option flags. Here we'll cause an extra error
1288 by disabling the blank-line feature:
1289
1290 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001291 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001292 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001293 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001294
Tim Peters1e277ee2004-08-07 05:37:52 +00001295 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001296
1297 >>> def setUp():
1298 ... import test.test_doctest
1299 ... test.test_doctest.sillySetup = True
1300
1301 >>> def tearDown():
1302 ... import test.test_doctest
1303 ... del test.test_doctest.sillySetup
1304
1305 Here, we installed a silly variable that the test expects:
1306
1307 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1308 ... setUp=setUp, tearDown=tearDown)
1309 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001310 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001311
1312 But the tearDown restores sanity:
1313
1314 >>> import test.test_doctest
1315 >>> test.test_doctest.sillySetup
1316 Traceback (most recent call last):
1317 ...
1318 AttributeError: 'module' object has no attribute 'sillySetup'
1319
1320 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001321 use a custom test_finder to to run just the test named bar.
1322 However, the test in the module docstring, and the two tests
1323 in the module __test__ dict, aren't filtered, so we actually
1324 run three tests besides bar's. The filtering mechanisms are
1325 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001326
1327 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001328 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001329 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1330 ... test_finder=finder)
1331 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001332 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001333 """
1334
1335def test_DocFileSuite():
1336 """We can test tests found in text files using a DocFileSuite.
1337
1338 We create a suite by providing the names of one or more text
1339 files that include examples:
1340
1341 >>> import unittest
1342 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1343 ... 'test_doctest2.txt')
1344 >>> suite.run(unittest.TestResult())
1345 <unittest.TestResult run=2 errors=0 failures=2>
1346
1347 The test files are looked for in the directory containing the
1348 calling module. A package keyword argument can be provided to
1349 specify a different relative location.
1350
1351 >>> import unittest
1352 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1353 ... 'test_doctest2.txt',
1354 ... package='test')
1355 >>> suite.run(unittest.TestResult())
1356 <unittest.TestResult run=2 errors=0 failures=2>
1357
1358 Note that '/' should be used as a path separator. It will be
1359 converted to a native separator at run time:
1360
1361
1362 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1363 >>> suite.run(unittest.TestResult())
1364 <unittest.TestResult run=1 errors=0 failures=1>
1365
1366 You can specify initial global variables:
1367
1368 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1369 ... 'test_doctest2.txt',
1370 ... globs={'favorite_color': 'blue'})
1371 >>> suite.run(unittest.TestResult())
1372 <unittest.TestResult run=2 errors=0 failures=1>
1373
1374 In this case, we supplied a missing favorite color. You can
1375 provide doctest options:
1376
1377 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1378 ... 'test_doctest2.txt',
1379 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1380 ... globs={'favorite_color': 'blue'})
1381 >>> suite.run(unittest.TestResult())
1382 <unittest.TestResult run=2 errors=0 failures=2>
1383
1384 And, you can provide setUp and tearDown functions:
1385
1386 You can supply setUp and teatDoen functions:
1387
1388 >>> def setUp():
1389 ... import test.test_doctest
1390 ... test.test_doctest.sillySetup = True
1391
1392 >>> def tearDown():
1393 ... import test.test_doctest
1394 ... del test.test_doctest.sillySetup
1395
1396 Here, we installed a silly variable that the test expects:
1397
1398 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1399 ... 'test_doctest2.txt',
1400 ... setUp=setUp, tearDown=tearDown)
1401 >>> suite.run(unittest.TestResult())
1402 <unittest.TestResult run=2 errors=0 failures=1>
1403
1404 But the tearDown restores sanity:
1405
1406 >>> import test.test_doctest
1407 >>> test.test_doctest.sillySetup
1408 Traceback (most recent call last):
1409 ...
1410 AttributeError: 'module' object has no attribute 'sillySetup'
1411
1412 """
1413
1414
Tim Peters8485b562004-08-04 18:46:34 +00001415######################################################################
1416## Main
1417######################################################################
1418
1419def test_main():
1420 # Check the doctest cases in doctest itself:
1421 test_support.run_doctest(doctest, verbosity=True)
1422 # Check the doctest cases defined here:
1423 from test import test_doctest
1424 test_support.run_doctest(test_doctest, verbosity=True)
1425
1426import trace, sys, re, StringIO
1427def test_coverage(coverdir):
1428 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1429 trace=0, count=1)
1430 tracer.run('reload(doctest); test_main()')
1431 r = tracer.results()
1432 print 'Writing coverage results...'
1433 r.write_results(show_missing=True, summary=True,
1434 coverdir=coverdir)
1435
1436if __name__ == '__main__':
1437 if '-c' in sys.argv:
1438 test_coverage('/tmp/doctest.cover')
1439 else:
1440 test_main()