blob: dec9110f3fdba03fd85e092d2dab677549c89155 [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
783The UNIFIED_DIFF flag causes failures that involve multi-line expected
784and actual outputs to be displayed using a unified diff:
785
786 >>> def f(x):
787 ... r'''
788 ... >>> print '\n'.join('abcdefg')
789 ... a
790 ... B
791 ... c
792 ... d
793 ... f
794 ... g
795 ... h
796 ... '''
797
798 >>> # Without the flag:
799 >>> test = doctest.DocTestFinder().find(f)[0]
800 >>> doctest.DocTestRunner(verbose=False).run(test)
801 **********************************************************************
802 Failure in example: print '\n'.join('abcdefg')
803 from line #1 of f
804 Expected:
805 a
806 B
807 c
808 d
809 f
810 g
811 h
812 Got:
813 a
814 b
815 c
816 d
817 e
818 f
819 g
820 (1, 1)
821
822 >>> # With the flag:
823 >>> test = doctest.DocTestFinder().find(f)[0]
824 >>> flags = doctest.UNIFIED_DIFF
825 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
826 **********************************************************************
827 Failure in example: print '\n'.join('abcdefg')
828 from line #1 of f
829 Differences (unified diff):
830 --- Expected
831 +++ Got
832 @@ -1,8 +1,8 @@
833 a
834 -B
835 +b
836 c
837 d
838 +e
839 f
840 g
841 -h
842 <BLANKLINE>
843 (1, 1)
844
845The CONTEXT_DIFF flag causes failures that involve multi-line expected
846and actual outputs to be displayed using a context diff:
847
848 >>> # Reuse f() from the UNIFIED_DIFF example, above.
849 >>> test = doctest.DocTestFinder().find(f)[0]
850 >>> flags = doctest.CONTEXT_DIFF
851 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
852 **********************************************************************
853 Failure in example: print '\n'.join('abcdefg')
854 from line #1 of f
855 Differences (context diff):
856 *** Expected
857 --- Got
858 ***************
859 *** 1,8 ****
860 a
861 ! B
862 c
863 d
864 f
865 g
866 - h
867 <BLANKLINE>
868 --- 1,8 ----
869 a
870 ! b
871 c
872 d
873 + e
874 f
875 g
876 <BLANKLINE>
877 (1, 1)
878"""
879 def option_directives(): r"""
880Tests of `DocTestRunner`'s option directive mechanism.
881
Edward Loper74bca7a2004-08-12 02:27:44 +0000882Option directives can be used to turn option flags on or off for a
883single example. To turn an option on for an example, follow that
884example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +0000885
886 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +0000887 ... >>> print range(10) # should fail: no ellipsis
888 ... [0, 1, ..., 9]
889 ...
890 ... >>> print range(10) # doctest: +ELLIPSIS
891 ... [0, 1, ..., 9]
892 ... '''
893 >>> test = doctest.DocTestFinder().find(f)[0]
894 >>> doctest.DocTestRunner(verbose=False).run(test)
895 **********************************************************************
896 Failure in example: print range(10) # should fail: no ellipsis
897 from line #1 of f
898 Expected: [0, 1, ..., 9]
899 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
900 (1, 2)
901
902To turn an option off for an example, follow that example with a
903comment of the form ``# doctest: -OPTION``:
904
905 >>> def f(x): r'''
906 ... >>> print range(10)
907 ... [0, 1, ..., 9]
908 ...
909 ... >>> # should fail: no ellipsis
910 ... >>> print range(10) # doctest: -ELLIPSIS
911 ... [0, 1, ..., 9]
912 ... '''
913 >>> test = doctest.DocTestFinder().find(f)[0]
914 >>> doctest.DocTestRunner(verbose=False,
915 ... optionflags=doctest.ELLIPSIS).run(test)
916 **********************************************************************
917 Failure in example: print range(10) # doctest: -ELLIPSIS
Edward Loperb51b2342004-08-17 16:37:12 +0000918 from line #5 of f
Edward Loper74bca7a2004-08-12 02:27:44 +0000919 Expected: [0, 1, ..., 9]
920 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
921 (1, 2)
922
923Option directives affect only the example that they appear with; they
924do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +0000925
Edward Loper74bca7a2004-08-12 02:27:44 +0000926 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +0000927 ... >>> print range(10) # Should fail: no ellipsis
928 ... [0, 1, ..., 9]
929 ...
Edward Loper74bca7a2004-08-12 02:27:44 +0000930 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000931 ... [0, 1, ..., 9]
932 ...
Tim Peters8485b562004-08-04 18:46:34 +0000933 ... >>> print range(10) # Should fail: no ellipsis
934 ... [0, 1, ..., 9]
935 ... '''
936 >>> test = doctest.DocTestFinder().find(f)[0]
937 >>> doctest.DocTestRunner(verbose=False).run(test)
938 **********************************************************************
939 Failure in example: print range(10) # Should fail: no ellipsis
940 from line #1 of f
941 Expected: [0, 1, ..., 9]
942 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
943 **********************************************************************
944 Failure in example: print range(10) # Should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +0000945 from line #7 of f
Tim Peters8485b562004-08-04 18:46:34 +0000946 Expected: [0, 1, ..., 9]
947 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
948 (2, 3)
949
Edward Loper74bca7a2004-08-12 02:27:44 +0000950Multiple options may be modified by a single option directive. They
951may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +0000952
953 >>> def f(x): r'''
954 ... >>> print range(10) # Should fail
955 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +0000956 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +0000957 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +0000958 ... [0, 1, ..., 9]
959 ... '''
960 >>> test = doctest.DocTestFinder().find(f)[0]
961 >>> doctest.DocTestRunner(verbose=False).run(test)
962 **********************************************************************
963 Failure in example: print range(10) # Should fail
964 from line #1 of f
965 Expected: [0, 1, ..., 9]
966 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
967 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +0000968
969 >>> def f(x): r'''
970 ... >>> print range(10) # Should fail
971 ... [0, 1, ..., 9]
972 ... >>> print range(10) # Should succeed
973 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
974 ... [0, 1, ..., 9]
975 ... '''
976 >>> test = doctest.DocTestFinder().find(f)[0]
977 >>> doctest.DocTestRunner(verbose=False).run(test)
978 **********************************************************************
979 Failure in example: print range(10) # Should fail
980 from line #1 of f
981 Expected: [0, 1, ..., 9]
982 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
983 (1, 2)
984
985 >>> def f(x): r'''
986 ... >>> print range(10) # Should fail
987 ... [0, 1, ..., 9]
988 ... >>> print range(10) # Should succeed
989 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
990 ... [0, 1, ..., 9]
991 ... '''
992 >>> test = doctest.DocTestFinder().find(f)[0]
993 >>> doctest.DocTestRunner(verbose=False).run(test)
994 **********************************************************************
995 Failure in example: print range(10) # Should fail
996 from line #1 of f
997 Expected: [0, 1, ..., 9]
998 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
999 (1, 2)
1000
1001The option directive may be put on the line following the source, as
1002long as a continuation prompt is used:
1003
1004 >>> def f(x): r'''
1005 ... >>> print range(10)
1006 ... ... # doctest: +ELLIPSIS
1007 ... [0, 1, ..., 9]
1008 ... '''
1009 >>> test = doctest.DocTestFinder().find(f)[0]
1010 >>> doctest.DocTestRunner(verbose=False).run(test)
1011 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001012
Edward Loper74bca7a2004-08-12 02:27:44 +00001013For examples with multi-line source, the option directive may appear
1014at the end of any line:
1015
1016 >>> def f(x): r'''
1017 ... >>> for x in range(10): # doctest: +ELLIPSIS
1018 ... ... print x,
1019 ... 0 1 2 ... 9
1020 ...
1021 ... >>> for x in range(10):
1022 ... ... print x, # doctest: +ELLIPSIS
1023 ... 0 1 2 ... 9
1024 ... '''
1025 >>> test = doctest.DocTestFinder().find(f)[0]
1026 >>> doctest.DocTestRunner(verbose=False).run(test)
1027 (0, 2)
1028
1029If more than one line of an example with multi-line source has an
1030option directive, then they are combined:
1031
1032 >>> def f(x): r'''
1033 ... Should fail (option directive not on the last line):
1034 ... >>> for x in range(10): # doctest: +ELLIPSIS
1035 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1036 ... 0 1 2...9
1037 ... '''
1038 >>> test = doctest.DocTestFinder().find(f)[0]
1039 >>> doctest.DocTestRunner(verbose=False).run(test)
1040 (0, 1)
1041
1042It is an error to have a comment of the form ``# doctest:`` that is
1043*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1044``OPTION`` is an option that has been registered with
1045`register_option`:
1046
1047 >>> # Error: Option not registered
1048 >>> s = '>>> print 12 #doctest: +BADOPTION'
1049 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1050 Traceback (most recent call last):
1051 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1052
1053 >>> # Error: No + or - prefix
1054 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1055 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1056 Traceback (most recent call last):
1057 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1058
1059It is an error to use an option directive on a line that contains no
1060source:
1061
1062 >>> s = '>>> # doctest: +ELLIPSIS'
1063 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1064 Traceback (most recent call last):
1065 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 +00001066"""
1067
1068def test_testsource(): r"""
1069Unit tests for `testsource()`.
1070
1071The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001072test with that name in that module, and converts it to a script. The
1073example code is converted to regular Python code. The surrounding
1074words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001075
1076 >>> import test.test_doctest
1077 >>> name = 'test.test_doctest.sample_func'
1078 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001079 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001080 #
Tim Peters8485b562004-08-04 18:46:34 +00001081 print sample_func(22)
1082 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001083 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001084 #
Edward Lopera5db6002004-08-12 02:41:30 +00001085 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001086
1087 >>> name = 'test.test_doctest.SampleNewStyleClass'
1088 >>> print doctest.testsource(test.test_doctest, name)
1089 print '1\n2\n3'
1090 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001091 ## 1
1092 ## 2
1093 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001094
1095 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1096 >>> print doctest.testsource(test.test_doctest, name)
1097 print SampleClass.a_classmethod(10)
1098 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001099 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001100 print SampleClass(0).a_classmethod(10)
1101 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001102 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001103"""
1104
1105def test_debug(): r"""
1106
1107Create a docstring that we want to debug:
1108
1109 >>> s = '''
1110 ... >>> x = 12
1111 ... >>> print x
1112 ... 12
1113 ... '''
1114
1115Create some fake stdin input, to feed to the debugger:
1116
1117 >>> import tempfile
1118 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1119 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1120 >>> fake_stdin.seek(0)
1121 >>> real_stdin = sys.stdin
1122 >>> sys.stdin = fake_stdin
1123
1124Run the debugger on the docstring, and then restore sys.stdin.
1125
Tim Peters8485b562004-08-04 18:46:34 +00001126 >>> try:
1127 ... doctest.debug_src(s)
1128 ... finally:
1129 ... sys.stdin = real_stdin
1130 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001131 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001132 > <string>(1)?()
1133 (Pdb) 12
1134 --Return--
1135 > <string>(1)?()->None
1136 (Pdb) 12
1137 (Pdb)
1138
1139"""
1140
Jim Fulton356fd192004-08-09 11:34:47 +00001141def test_pdb_set_trace():
1142 r"""Using pdb.set_trace from a doctest
1143
Tim Peters413ced62004-08-09 15:43:47 +00001144 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001145 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001146 you use it. The doctest module changes sys.stdout so that it can
1147 capture program output. It also temporarily replaces pdb.set_trace
1148 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001149 see debugger output.
1150
1151 >>> doc = '''
1152 ... >>> x = 42
1153 ... >>> import pdb; pdb.set_trace()
1154 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001155 >>> parser = doctest.DocTestParser()
1156 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001157 >>> runner = doctest.DocTestRunner(verbose=False)
1158
1159 To demonstrate this, we'll create a fake standard input that
1160 captures our debugger input:
1161
1162 >>> import tempfile
1163 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1164 >>> fake_stdin.write('\n'.join([
1165 ... 'up', # up out of pdb.set_trace
1166 ... 'up', # up again to get out of our wrapper
1167 ... 'print x', # print data defined by the example
1168 ... 'continue', # stop debugging
1169 ... '']))
1170 >>> fake_stdin.seek(0)
1171 >>> real_stdin = sys.stdin
1172 >>> sys.stdin = fake_stdin
1173
Edward Loper74bca7a2004-08-12 02:27:44 +00001174 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001175 --Return--
1176 > ...set_trace()->None
1177 -> Pdb().set_trace()
1178 (Pdb) > ...set_trace()
1179 -> real_pdb_set_trace()
1180 (Pdb) > <string>(1)?()
1181 (Pdb) 42
1182 (Pdb) (0, 2)
1183
1184 >>> sys.stdin = real_stdin
1185 >>> fake_stdin.close()
1186
1187 You can also put pdb.set_trace in a function called from a test:
1188
1189 >>> def calls_set_trace():
1190 ... y=2
1191 ... import pdb; pdb.set_trace()
1192
1193 >>> doc = '''
1194 ... >>> x=1
1195 ... >>> calls_set_trace()
1196 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001197 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001198 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1199 >>> fake_stdin.write('\n'.join([
1200 ... 'up', # up out of pdb.set_trace
1201 ... 'up', # up again to get out of our wrapper
1202 ... 'print y', # print data defined in the function
1203 ... 'up', # out of function
1204 ... 'print x', # print data defined by the example
1205 ... 'continue', # stop debugging
1206 ... '']))
1207 >>> fake_stdin.seek(0)
1208 >>> real_stdin = sys.stdin
1209 >>> sys.stdin = fake_stdin
1210
Edward Loper74bca7a2004-08-12 02:27:44 +00001211 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001212 --Return--
1213 > ...set_trace()->None
1214 -> Pdb().set_trace()
1215 (Pdb) ...set_trace()
1216 -> real_pdb_set_trace()
1217 (Pdb) > <string>(3)calls_set_trace()
1218 (Pdb) 2
1219 (Pdb) > <string>(1)?()
1220 (Pdb) 1
1221 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001222 """
1223
Tim Peters19397e52004-08-06 22:02:59 +00001224def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001225 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001226
1227 We create a Suite by providing a module. A module can be provided
1228 by passing a module object:
1229
1230 >>> import unittest
1231 >>> import test.sample_doctest
1232 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1233 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001234 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001235
1236 We can also supply the module by name:
1237
1238 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1239 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001240 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001241
1242 We can use the current module:
1243
1244 >>> suite = test.sample_doctest.test_suite()
1245 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001246 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001247
1248 We can supply global variables. If we pass globs, they will be
1249 used instead of the module globals. Here we'll pass an empty
1250 globals, triggering an extra error:
1251
1252 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1253 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001254 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001255
1256 Alternatively, we can provide extra globals. Here we'll make an
1257 error go away by providing an extra global variable:
1258
1259 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1260 ... extraglobs={'y': 1})
1261 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001262 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001263
1264 You can pass option flags. Here we'll cause an extra error
1265 by disabling the blank-line feature:
1266
1267 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001268 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001269 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001270 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001271
Tim Peters1e277ee2004-08-07 05:37:52 +00001272 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001273
1274 >>> def setUp():
1275 ... import test.test_doctest
1276 ... test.test_doctest.sillySetup = True
1277
1278 >>> def tearDown():
1279 ... import test.test_doctest
1280 ... del test.test_doctest.sillySetup
1281
1282 Here, we installed a silly variable that the test expects:
1283
1284 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1285 ... setUp=setUp, tearDown=tearDown)
1286 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001287 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001288
1289 But the tearDown restores sanity:
1290
1291 >>> import test.test_doctest
1292 >>> test.test_doctest.sillySetup
1293 Traceback (most recent call last):
1294 ...
1295 AttributeError: 'module' object has no attribute 'sillySetup'
1296
1297 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001298 use a custom test_finder to to run just the test named bar.
1299 However, the test in the module docstring, and the two tests
1300 in the module __test__ dict, aren't filtered, so we actually
1301 run three tests besides bar's. The filtering mechanisms are
1302 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001303
1304 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001305 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001306 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1307 ... test_finder=finder)
1308 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001309 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001310 """
1311
1312def test_DocFileSuite():
1313 """We can test tests found in text files using a DocFileSuite.
1314
1315 We create a suite by providing the names of one or more text
1316 files that include examples:
1317
1318 >>> import unittest
1319 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1320 ... 'test_doctest2.txt')
1321 >>> suite.run(unittest.TestResult())
1322 <unittest.TestResult run=2 errors=0 failures=2>
1323
1324 The test files are looked for in the directory containing the
1325 calling module. A package keyword argument can be provided to
1326 specify a different relative location.
1327
1328 >>> import unittest
1329 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1330 ... 'test_doctest2.txt',
1331 ... package='test')
1332 >>> suite.run(unittest.TestResult())
1333 <unittest.TestResult run=2 errors=0 failures=2>
1334
1335 Note that '/' should be used as a path separator. It will be
1336 converted to a native separator at run time:
1337
1338
1339 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1340 >>> suite.run(unittest.TestResult())
1341 <unittest.TestResult run=1 errors=0 failures=1>
1342
1343 You can specify initial global variables:
1344
1345 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1346 ... 'test_doctest2.txt',
1347 ... globs={'favorite_color': 'blue'})
1348 >>> suite.run(unittest.TestResult())
1349 <unittest.TestResult run=2 errors=0 failures=1>
1350
1351 In this case, we supplied a missing favorite color. You can
1352 provide doctest options:
1353
1354 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1355 ... 'test_doctest2.txt',
1356 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1357 ... globs={'favorite_color': 'blue'})
1358 >>> suite.run(unittest.TestResult())
1359 <unittest.TestResult run=2 errors=0 failures=2>
1360
1361 And, you can provide setUp and tearDown functions:
1362
1363 You can supply setUp and teatDoen functions:
1364
1365 >>> def setUp():
1366 ... import test.test_doctest
1367 ... test.test_doctest.sillySetup = True
1368
1369 >>> def tearDown():
1370 ... import test.test_doctest
1371 ... del test.test_doctest.sillySetup
1372
1373 Here, we installed a silly variable that the test expects:
1374
1375 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1376 ... 'test_doctest2.txt',
1377 ... setUp=setUp, tearDown=tearDown)
1378 >>> suite.run(unittest.TestResult())
1379 <unittest.TestResult run=2 errors=0 failures=1>
1380
1381 But the tearDown restores sanity:
1382
1383 >>> import test.test_doctest
1384 >>> test.test_doctest.sillySetup
1385 Traceback (most recent call last):
1386 ...
1387 AttributeError: 'module' object has no attribute 'sillySetup'
1388
1389 """
1390
1391
Tim Peters8485b562004-08-04 18:46:34 +00001392######################################################################
1393## Main
1394######################################################################
1395
1396def test_main():
1397 # Check the doctest cases in doctest itself:
1398 test_support.run_doctest(doctest, verbosity=True)
1399 # Check the doctest cases defined here:
1400 from test import test_doctest
1401 test_support.run_doctest(test_doctest, verbosity=True)
1402
1403import trace, sys, re, StringIO
1404def test_coverage(coverdir):
1405 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1406 trace=0, count=1)
1407 tracer.run('reload(doctest); test_main()')
1408 r = tracer.results()
1409 print 'Writing coverage results...'
1410 r.write_results(show_missing=True, summary=True,
1411 coverdir=coverdir)
1412
1413if __name__ == '__main__':
1414 if '-c' in sys.argv:
1415 test_coverage('/tmp/doctest.cover')
1416 else:
1417 test_main()