blob: 1268e6a29b912e64025dea0ff0f7f394dc1961b7 [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
Tim Petersa7def722004-08-23 22:13:22 +00007import warnings
Tim Peters8485b562004-08-04 18:46:34 +00008
9######################################################################
10## Sample Objects (used by test cases)
11######################################################################
12
13def sample_func(v):
14 """
Tim Peters19397e52004-08-06 22:02:59 +000015 Blah blah
16
Tim Peters8485b562004-08-04 18:46:34 +000017 >>> print sample_func(22)
18 44
Tim Peters19397e52004-08-06 22:02:59 +000019
20 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000021 """
22 return v+v
23
24class SampleClass:
25 """
26 >>> print 1
27 1
28 """
29 def __init__(self, val):
30 """
31 >>> print SampleClass(12).get()
32 12
33 """
34 self.val = val
35
36 def double(self):
37 """
38 >>> print SampleClass(12).double().get()
39 24
40 """
41 return SampleClass(self.val + self.val)
42
43 def get(self):
44 """
45 >>> print SampleClass(-5).get()
46 -5
47 """
48 return self.val
49
50 def a_staticmethod(v):
51 """
52 >>> print SampleClass.a_staticmethod(10)
53 11
54 """
55 return v+1
56 a_staticmethod = staticmethod(a_staticmethod)
57
58 def a_classmethod(cls, v):
59 """
60 >>> print SampleClass.a_classmethod(10)
61 12
62 >>> print SampleClass(0).a_classmethod(10)
63 12
64 """
65 return v+2
66 a_classmethod = classmethod(a_classmethod)
67
68 a_property = property(get, doc="""
69 >>> print SampleClass(22).a_property
70 22
71 """)
72
73 class NestedClass:
74 """
75 >>> x = SampleClass.NestedClass(5)
76 >>> y = x.square()
77 >>> print y.get()
78 25
79 """
80 def __init__(self, val=0):
81 """
82 >>> print SampleClass.NestedClass().get()
83 0
84 """
85 self.val = val
86 def square(self):
87 return SampleClass.NestedClass(self.val*self.val)
88 def get(self):
89 return self.val
90
91class SampleNewStyleClass(object):
92 r"""
93 >>> print '1\n2\n3'
94 1
95 2
96 3
97 """
98 def __init__(self, val):
99 """
100 >>> print SampleNewStyleClass(12).get()
101 12
102 """
103 self.val = val
104
105 def double(self):
106 """
107 >>> print SampleNewStyleClass(12).double().get()
108 24
109 """
110 return SampleNewStyleClass(self.val + self.val)
111
112 def get(self):
113 """
114 >>> print SampleNewStyleClass(-5).get()
115 -5
116 """
117 return self.val
118
119######################################################################
120## Test Cases
121######################################################################
122
123def test_Example(): r"""
124Unit tests for the `Example` class.
125
126Example is a simple container class that holds a source code string,
127an expected output string, and a line number (within the docstring):
128
129 >>> example = doctest.Example('print 1', '1\n', 0)
130 >>> (example.source, example.want, example.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000131 ('print 1\n', '1\n', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000132
Tim Petersbb431472004-08-09 03:51:46 +0000133The `source` string ends in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000134
Tim Petersbb431472004-08-09 03:51:46 +0000135 Source spans a single line: no terminating newline.
Tim Peters8485b562004-08-04 18:46:34 +0000136 >>> e = doctest.Example('print 1', '1\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000137 >>> e.source, e.want
138 ('print 1\n', '1\n')
139
Tim Peters8485b562004-08-04 18:46:34 +0000140 >>> e = doctest.Example('print 1\n', '1\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000141 >>> e.source, e.want
142 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000143
Tim Petersbb431472004-08-09 03:51:46 +0000144 Source spans multiple lines: require terminating newline.
Tim Peters8485b562004-08-04 18:46:34 +0000145 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000146 >>> e.source, e.want
147 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000148
Tim Petersbb431472004-08-09 03:51:46 +0000149 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n', 0)
150 >>> e.source, e.want
151 ('print 1;\nprint 2\n', '1\n2\n')
152
153The `want` string ends with a newline, unless it's the empty string:
Tim Peters8485b562004-08-04 18:46:34 +0000154
155 >>> e = doctest.Example('print 1', '1\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000156 >>> e.source, e.want
157 ('print 1\n', '1\n')
158
Tim Peters8485b562004-08-04 18:46:34 +0000159 >>> e = doctest.Example('print 1', '1', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000160 >>> e.source, e.want
161 ('print 1\n', '1\n')
162
Tim Peters8485b562004-08-04 18:46:34 +0000163 >>> e = doctest.Example('print', '', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000164 >>> e.source, e.want
165 ('print\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000166"""
167
168def test_DocTest(): r"""
169Unit tests for the `DocTest` class.
170
171DocTest is a collection of examples, extracted from a docstring, along
172with information about where the docstring comes from (a name,
173filename, and line number). The docstring is parsed by the `DocTest`
174constructor:
175
176 >>> docstring = '''
177 ... >>> print 12
178 ... 12
179 ...
180 ... Non-example text.
181 ...
182 ... >>> print 'another\example'
183 ... another
184 ... example
185 ... '''
186 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000187 >>> parser = doctest.DocTestParser()
188 >>> test = parser.get_doctest(docstring, globs, 'some_test',
189 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000190 >>> print test
191 <DocTest some_test from some_file:20 (2 examples)>
192 >>> len(test.examples)
193 2
194 >>> e1, e2 = test.examples
195 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000196 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000197 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000198 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000199
200Source information (name, filename, and line number) is available as
201attributes on the doctest object:
202
203 >>> (test.name, test.filename, test.lineno)
204 ('some_test', 'some_file', 20)
205
206The line number of an example within its containing file is found by
207adding the line number of the example and the line number of its
208containing test:
209
210 >>> test.lineno + e1.lineno
211 21
212 >>> test.lineno + e2.lineno
213 26
214
215If the docstring contains inconsistant leading whitespace in the
216expected output of an example, then `DocTest` will raise a ValueError:
217
218 >>> docstring = r'''
219 ... >>> print 'bad\nindentation'
220 ... bad
221 ... indentation
222 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000223 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000224 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000225 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: ' indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000226
227If the docstring contains inconsistent leading whitespace on
228continuation lines, then `DocTest` will raise a ValueError:
229
230 >>> docstring = r'''
231 ... >>> print ('bad indentation',
232 ... ... 2)
233 ... ('bad', 'indentation')
234 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000235 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000236 Traceback (most recent call last):
237 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: ' ... 2)'
238
239If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
240will raise a ValueError:
241
242 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000243 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000244 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000245 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
246
247If there's no blank space after a PS2 prompt ('...'), then `DocTest`
248will raise a ValueError:
249
250 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000251 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000252 Traceback (most recent call last):
253 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
254
Tim Peters8485b562004-08-04 18:46:34 +0000255"""
256
Tim Peters8485b562004-08-04 18:46:34 +0000257def test_DocTestFinder(): r"""
258Unit tests for the `DocTestFinder` class.
259
260DocTestFinder is used to extract DocTests from an object's docstring
261and the docstrings of its contained objects. It can be used with
262modules, functions, classes, methods, staticmethods, classmethods, and
263properties.
264
265Finding Tests in Functions
266~~~~~~~~~~~~~~~~~~~~~~~~~~
267For a function whose docstring contains examples, DocTestFinder.find()
268will return a single test (for that function's docstring):
269
Tim Peters8485b562004-08-04 18:46:34 +0000270 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000271
272We'll simulate a __file__ attr that ends in pyc:
273
274 >>> import test.test_doctest
275 >>> old = test.test_doctest.__file__
276 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
277
Tim Peters8485b562004-08-04 18:46:34 +0000278 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000279
Edward Loper74bca7a2004-08-12 02:27:44 +0000280 >>> print tests # doctest: +ELLIPSIS
Tim Petersa7def722004-08-23 22:13:22 +0000281 [<DocTest sample_func from ...:13 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000282
Jim Fulton07a349c2004-08-22 14:10:00 +0000283 >>> tests[0].filename
284 'test_doctest.py'
285
286 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000287
Jim Fulton07a349c2004-08-22 14:10:00 +0000288
Tim Peters8485b562004-08-04 18:46:34 +0000289 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000290 >>> (e.source, e.want, e.lineno)
291 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000292
Tim Peters8485b562004-08-04 18:46:34 +0000293If an object has no docstring, then a test is not created for it:
294
295 >>> def no_docstring(v):
296 ... pass
297 >>> finder.find(no_docstring)
298 []
299
300If the function has a docstring with no examples, then a test with no
301examples is returned. (This lets `DocTestRunner` collect statistics
302about which functions have no tests -- but is that useful? And should
303an empty test also be created when there's no docstring?)
304
305 >>> def no_examples(v):
306 ... ''' no doctest examples '''
307 >>> finder.find(no_examples)
308 [<DocTest no_examples from None:1 (no examples)>]
309
310Finding Tests in Classes
311~~~~~~~~~~~~~~~~~~~~~~~~
312For a class, DocTestFinder will create a test for the class's
313docstring, and will recursively explore its contents, including
314methods, classmethods, staticmethods, properties, and nested classes.
315
316 >>> finder = doctest.DocTestFinder()
317 >>> tests = finder.find(SampleClass)
318 >>> tests.sort()
319 >>> for t in tests:
320 ... print '%2s %s' % (len(t.examples), t.name)
321 1 SampleClass
322 3 SampleClass.NestedClass
323 1 SampleClass.NestedClass.__init__
324 1 SampleClass.__init__
325 2 SampleClass.a_classmethod
326 1 SampleClass.a_property
327 1 SampleClass.a_staticmethod
328 1 SampleClass.double
329 1 SampleClass.get
330
331New-style classes are also supported:
332
333 >>> tests = finder.find(SampleNewStyleClass)
334 >>> tests.sort()
335 >>> for t in tests:
336 ... print '%2s %s' % (len(t.examples), t.name)
337 1 SampleNewStyleClass
338 1 SampleNewStyleClass.__init__
339 1 SampleNewStyleClass.double
340 1 SampleNewStyleClass.get
341
342Finding Tests in Modules
343~~~~~~~~~~~~~~~~~~~~~~~~
344For a module, DocTestFinder will create a test for the class's
345docstring, and will recursively explore its contents, including
346functions, classes, and the `__test__` dictionary, if it exists:
347
348 >>> # A module
349 >>> import new
350 >>> m = new.module('some_module')
351 >>> def triple(val):
352 ... '''
353 ... >>> print tripple(11)
354 ... 33
355 ... '''
356 ... return val*3
357 >>> m.__dict__.update({
358 ... 'sample_func': sample_func,
359 ... 'SampleClass': SampleClass,
360 ... '__doc__': '''
361 ... Module docstring.
362 ... >>> print 'module'
363 ... module
364 ... ''',
365 ... '__test__': {
366 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
367 ... 'c': triple}})
368
369 >>> finder = doctest.DocTestFinder()
370 >>> # Use module=test.test_doctest, to prevent doctest from
371 >>> # ignoring the objects since they weren't defined in m.
372 >>> import test.test_doctest
373 >>> tests = finder.find(m, module=test.test_doctest)
374 >>> tests.sort()
375 >>> for t in tests:
376 ... print '%2s %s' % (len(t.examples), t.name)
377 1 some_module
378 1 some_module.SampleClass
379 3 some_module.SampleClass.NestedClass
380 1 some_module.SampleClass.NestedClass.__init__
381 1 some_module.SampleClass.__init__
382 2 some_module.SampleClass.a_classmethod
383 1 some_module.SampleClass.a_property
384 1 some_module.SampleClass.a_staticmethod
385 1 some_module.SampleClass.double
386 1 some_module.SampleClass.get
387 1 some_module.c
388 2 some_module.d
389 1 some_module.sample_func
390
391Duplicate Removal
392~~~~~~~~~~~~~~~~~
393If a single object is listed twice (under different names), then tests
394will only be generated for it once:
395
Tim Petersf3f57472004-08-08 06:11:48 +0000396 >>> from test import doctest_aliases
397 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000398 >>> tests.sort()
399 >>> print len(tests)
400 2
401 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000402 test.doctest_aliases.TwoNames
403
404 TwoNames.f and TwoNames.g are bound to the same object.
405 We can't guess which will be found in doctest's traversal of
406 TwoNames.__dict__ first, so we have to allow for either.
407
408 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000409 True
410
411Filter Functions
412~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000413A filter function can be used to restrict which objects get examined,
414but this is temporary, undocumented internal support for testmod's
415deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000416
417 >>> def namefilter(prefix, base):
418 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000419 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000420 >>> tests.sort()
421 >>> for t in tests:
422 ... print '%2s %s' % (len(t.examples), t.name)
423 1 SampleClass
424 3 SampleClass.NestedClass
425 1 SampleClass.NestedClass.__init__
426 1 SampleClass.__init__
427 1 SampleClass.double
428 1 SampleClass.get
429
Tim Peters8485b562004-08-04 18:46:34 +0000430If a given object is filtered out, then none of the objects that it
431contains will be added either:
432
433 >>> def namefilter(prefix, base):
434 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000435 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000436 >>> tests.sort()
437 >>> for t in tests:
438 ... print '%2s %s' % (len(t.examples), t.name)
439 1 SampleClass
440 1 SampleClass.__init__
441 2 SampleClass.a_classmethod
442 1 SampleClass.a_property
443 1 SampleClass.a_staticmethod
444 1 SampleClass.double
445 1 SampleClass.get
446
Tim Petersf727c6c2004-08-08 01:48:59 +0000447The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000448object explicitly passed to DocTestFinder:
449
450 >>> def namefilter(prefix, base):
451 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000452 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000453 >>> len(tests)
454 9
455
456Turning off Recursion
457~~~~~~~~~~~~~~~~~~~~~
458DocTestFinder can be told not to look for tests in contained objects
459using the `recurse` flag:
460
461 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
462 >>> tests.sort()
463 >>> for t in tests:
464 ... print '%2s %s' % (len(t.examples), t.name)
465 1 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000466
467Line numbers
468~~~~~~~~~~~~
469DocTestFinder finds the line number of each example:
470
471 >>> def f(x):
472 ... '''
473 ... >>> x = 12
474 ...
475 ... some text
476 ...
477 ... >>> # examples are not created for comments & bare prompts.
478 ... >>>
479 ... ...
480 ...
481 ... >>> for x in range(10):
482 ... ... print x,
483 ... 0 1 2 3 4 5 6 7 8 9
484 ... >>> x/2
485 ... 6
486 ... '''
487 >>> test = doctest.DocTestFinder().find(f)[0]
488 >>> [e.lineno for e in test.examples]
489 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000490"""
491
492class test_DocTestRunner:
493 def basics(): r"""
494Unit tests for the `DocTestRunner` class.
495
496DocTestRunner is used to run DocTest test cases, and to accumulate
497statistics. Here's a simple DocTest case we can use:
498
499 >>> def f(x):
500 ... '''
501 ... >>> x = 12
502 ... >>> print x
503 ... 12
504 ... >>> x/2
505 ... 6
506 ... '''
507 >>> test = doctest.DocTestFinder().find(f)[0]
508
509The main DocTestRunner interface is the `run` method, which runs a
510given DocTest case in a given namespace (globs). It returns a tuple
511`(f,t)`, where `f` is the number of failed tests and `t` is the number
512of tried tests.
513
514 >>> doctest.DocTestRunner(verbose=False).run(test)
515 (0, 3)
516
517If any example produces incorrect output, then the test runner reports
518the failure and proceeds to the next example:
519
520 >>> def f(x):
521 ... '''
522 ... >>> x = 12
523 ... >>> print x
524 ... 14
525 ... >>> x/2
526 ... 6
527 ... '''
528 >>> test = doctest.DocTestFinder().find(f)[0]
529 >>> doctest.DocTestRunner(verbose=True).run(test)
530 Trying: x = 12
531 Expecting: nothing
532 ok
533 Trying: print x
534 Expecting: 14
535 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000536 Line 3, in f
537 Failed example:
538 print x
539 Expected:
540 14
541 Got:
542 12
Tim Peters8485b562004-08-04 18:46:34 +0000543 Trying: x/2
544 Expecting: 6
545 ok
546 (1, 3)
547"""
548 def verbose_flag(): r"""
549The `verbose` flag makes the test runner generate more detailed
550output:
551
552 >>> def f(x):
553 ... '''
554 ... >>> x = 12
555 ... >>> print x
556 ... 12
557 ... >>> x/2
558 ... 6
559 ... '''
560 >>> test = doctest.DocTestFinder().find(f)[0]
561
562 >>> doctest.DocTestRunner(verbose=True).run(test)
563 Trying: x = 12
564 Expecting: nothing
565 ok
566 Trying: print x
567 Expecting: 12
568 ok
569 Trying: x/2
570 Expecting: 6
571 ok
572 (0, 3)
573
574If the `verbose` flag is unspecified, then the output will be verbose
575iff `-v` appears in sys.argv:
576
577 >>> # Save the real sys.argv list.
578 >>> old_argv = sys.argv
579
580 >>> # If -v does not appear in sys.argv, then output isn't verbose.
581 >>> sys.argv = ['test']
582 >>> doctest.DocTestRunner().run(test)
583 (0, 3)
584
585 >>> # If -v does appear in sys.argv, then output is verbose.
586 >>> sys.argv = ['test', '-v']
587 >>> doctest.DocTestRunner().run(test)
588 Trying: x = 12
589 Expecting: nothing
590 ok
591 Trying: print x
592 Expecting: 12
593 ok
594 Trying: x/2
595 Expecting: 6
596 ok
597 (0, 3)
598
599 >>> # Restore sys.argv
600 >>> sys.argv = old_argv
601
602In the remaining examples, the test runner's verbosity will be
603explicitly set, to ensure that the test behavior is consistent.
604 """
605 def exceptions(): r"""
606Tests of `DocTestRunner`'s exception handling.
607
608An expected exception is specified with a traceback message. The
609lines between the first line and the type/value may be omitted or
610replaced with any other string:
611
612 >>> def f(x):
613 ... '''
614 ... >>> x = 12
615 ... >>> print x/0
616 ... Traceback (most recent call last):
617 ... ZeroDivisionError: integer division or modulo by zero
618 ... '''
619 >>> test = doctest.DocTestFinder().find(f)[0]
620 >>> doctest.DocTestRunner(verbose=False).run(test)
621 (0, 2)
622
623An example may generate output before it raises an exception; if it
624does, then the output must match the expected output:
625
626 >>> def f(x):
627 ... '''
628 ... >>> x = 12
629 ... >>> print 'pre-exception output', x/0
630 ... pre-exception output
631 ... Traceback (most recent call last):
632 ... ZeroDivisionError: integer division or modulo by zero
633 ... '''
634 >>> test = doctest.DocTestFinder().find(f)[0]
635 >>> doctest.DocTestRunner(verbose=False).run(test)
636 (0, 2)
637
638Exception messages may contain newlines:
639
640 >>> def f(x):
641 ... r'''
642 ... >>> raise ValueError, 'multi\nline\nmessage'
643 ... Traceback (most recent call last):
644 ... ValueError: multi
645 ... line
646 ... message
647 ... '''
648 >>> test = doctest.DocTestFinder().find(f)[0]
649 >>> doctest.DocTestRunner(verbose=False).run(test)
650 (0, 1)
651
652If an exception is expected, but an exception with the wrong type or
653message is raised, then it is reported as a failure:
654
655 >>> def f(x):
656 ... r'''
657 ... >>> raise ValueError, 'message'
658 ... Traceback (most recent call last):
659 ... ValueError: wrong message
660 ... '''
661 >>> test = doctest.DocTestFinder().find(f)[0]
662 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000663 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000664 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000665 Line 2, in f
666 Failed example:
667 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000668 Expected:
669 Traceback (most recent call last):
670 ValueError: wrong message
671 Got:
672 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000673 ...
Tim Peters8485b562004-08-04 18:46:34 +0000674 ValueError: message
675 (1, 1)
676
677If an exception is raised but not expected, then it is reported as an
678unexpected exception:
679
Tim Peters8485b562004-08-04 18:46:34 +0000680 >>> def f(x):
681 ... r'''
682 ... >>> 1/0
683 ... 0
684 ... '''
685 >>> test = doctest.DocTestFinder().find(f)[0]
686 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000687 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000688 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000689 Line 2, in f
690 Failed example:
691 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000692 Exception raised:
693 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000694 ...
Tim Peters8485b562004-08-04 18:46:34 +0000695 ZeroDivisionError: integer division or modulo by zero
696 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000697"""
698 def optionflags(): r"""
699Tests of `DocTestRunner`'s option flag handling.
700
701Several option flags can be used to customize the behavior of the test
702runner. These are defined as module constants in doctest, and passed
703to the DocTestRunner constructor (multiple constants should be or-ed
704together).
705
706The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
707and 1/0:
708
709 >>> def f(x):
710 ... '>>> True\n1\n'
711
712 >>> # Without the flag:
713 >>> test = doctest.DocTestFinder().find(f)[0]
714 >>> doctest.DocTestRunner(verbose=False).run(test)
715 (0, 1)
716
717 >>> # With the flag:
718 >>> test = doctest.DocTestFinder().find(f)[0]
719 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
720 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
721 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000722 Line 1, in f
723 Failed example:
724 True
725 Expected:
726 1
727 Got:
728 True
Tim Peters8485b562004-08-04 18:46:34 +0000729 (1, 1)
730
731The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
732and the '<BLANKLINE>' marker:
733
734 >>> def f(x):
735 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
736
737 >>> # Without the flag:
738 >>> test = doctest.DocTestFinder().find(f)[0]
739 >>> doctest.DocTestRunner(verbose=False).run(test)
740 (0, 1)
741
742 >>> # With the flag:
743 >>> test = doctest.DocTestFinder().find(f)[0]
744 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
745 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
746 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000747 Line 1, in f
748 Failed example:
749 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000750 Expected:
751 a
752 <BLANKLINE>
753 b
754 Got:
755 a
756 <BLANKLINE>
757 b
758 (1, 1)
759
760The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
761treated as equal:
762
763 >>> def f(x):
764 ... '>>> print 1, 2, 3\n 1 2\n 3'
765
766 >>> # Without the flag:
767 >>> test = doctest.DocTestFinder().find(f)[0]
768 >>> doctest.DocTestRunner(verbose=False).run(test)
769 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000770 Line 1, in f
771 Failed example:
772 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000773 Expected:
774 1 2
775 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000776 Got:
777 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000778 (1, 1)
779
780 >>> # With the flag:
781 >>> test = doctest.DocTestFinder().find(f)[0]
782 >>> flags = doctest.NORMALIZE_WHITESPACE
783 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
784 (0, 1)
785
Tim Peters026f8dc2004-08-19 16:38:58 +0000786 An example from the docs:
787 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
788 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
789 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
790
Tim Peters8485b562004-08-04 18:46:34 +0000791The ELLIPSIS flag causes ellipsis marker ("...") in the expected
792output to match any substring in the actual output:
793
794 >>> def f(x):
795 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
796
797 >>> # Without the flag:
798 >>> test = doctest.DocTestFinder().find(f)[0]
799 >>> doctest.DocTestRunner(verbose=False).run(test)
800 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000801 Line 1, in f
802 Failed example:
803 print range(15)
804 Expected:
805 [0, 1, 2, ..., 14]
806 Got:
807 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +0000808 (1, 1)
809
810 >>> # With the flag:
811 >>> test = doctest.DocTestFinder().find(f)[0]
812 >>> flags = doctest.ELLIPSIS
813 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
814 (0, 1)
815
Tim Peterse594bee2004-08-22 01:47:51 +0000816 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +0000817
818 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +0000819 ... print i**2, #doctest: +ELLIPSIS
820 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +0000821
Tim Peters026f8dc2004-08-19 16:38:58 +0000822 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000823
824 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +0000825 ... print i,
826 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +0000827
Tim Peters026f8dc2004-08-19 16:38:58 +0000828 Examples from the docs:
829
830 >>> print range(20) # doctest:+ELLIPSIS
831 [0, 1, ..., 18, 19]
832
833 >>> print range(20) # doctest: +ELLIPSIS
834 ... # doctest: +NORMALIZE_WHITESPACE
835 [0, 1, ..., 18, 19]
836
Tim Peters8485b562004-08-04 18:46:34 +0000837The UNIFIED_DIFF flag causes failures that involve multi-line expected
838and actual outputs to be displayed using a unified diff:
839
840 >>> def f(x):
841 ... r'''
842 ... >>> print '\n'.join('abcdefg')
843 ... a
844 ... B
845 ... c
846 ... d
847 ... f
848 ... g
849 ... h
850 ... '''
851
852 >>> # Without the flag:
853 >>> test = doctest.DocTestFinder().find(f)[0]
854 >>> doctest.DocTestRunner(verbose=False).run(test)
855 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000856 Line 2, in f
857 Failed example:
858 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000859 Expected:
860 a
861 B
862 c
863 d
864 f
865 g
866 h
867 Got:
868 a
869 b
870 c
871 d
872 e
873 f
874 g
875 (1, 1)
876
877 >>> # With the flag:
878 >>> test = doctest.DocTestFinder().find(f)[0]
879 >>> flags = doctest.UNIFIED_DIFF
880 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
881 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000882 Line 2, in f
883 Failed example:
884 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000885 Differences (unified diff):
886 --- Expected
887 +++ Got
888 @@ -1,8 +1,8 @@
889 a
890 -B
891 +b
892 c
893 d
894 +e
895 f
896 g
897 -h
898 <BLANKLINE>
899 (1, 1)
900
901The CONTEXT_DIFF flag causes failures that involve multi-line expected
902and actual outputs to be displayed using a context diff:
903
904 >>> # Reuse f() from the UNIFIED_DIFF example, above.
905 >>> test = doctest.DocTestFinder().find(f)[0]
906 >>> flags = doctest.CONTEXT_DIFF
907 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
908 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000909 Line 2, in f
910 Failed example:
911 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000912 Differences (context diff):
913 *** Expected
914 --- Got
915 ***************
916 *** 1,8 ****
917 a
918 ! B
919 c
920 d
921 f
922 g
923 - h
924 <BLANKLINE>
925 --- 1,8 ----
926 a
927 ! b
928 c
929 d
930 + e
931 f
932 g
933 <BLANKLINE>
934 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +0000935
936
937The NDIFF_DIFF flag causes failures to use the difflib.Differ algorithm
938used by the popular ndiff.py utility. This does intraline difference
939marking, as well as interline differences.
940
941 >>> def f(x):
942 ... r'''
943 ... >>> print "a b c d e f g h i j k l m"
944 ... a b c d e f g h i j k 1 m
945 ... '''
946 >>> test = doctest.DocTestFinder().find(f)[0]
947 >>> flags = doctest.NDIFF_DIFF
948 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
949 **********************************************************************
950 Line 2, in f
951 Failed example:
952 print "a b c d e f g h i j k l m"
953 Differences (ndiff with -expected +actual):
954 - a b c d e f g h i j k 1 m
955 ? ^
956 + a b c d e f g h i j k l m
957 ? + ++ ^
958 <BLANKLINE>
959 (1, 1)
960 """
961
Tim Peters8485b562004-08-04 18:46:34 +0000962 def option_directives(): r"""
963Tests of `DocTestRunner`'s option directive mechanism.
964
Edward Loper74bca7a2004-08-12 02:27:44 +0000965Option directives can be used to turn option flags on or off for a
966single example. To turn an option on for an example, follow that
967example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +0000968
969 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +0000970 ... >>> print range(10) # should fail: no ellipsis
971 ... [0, 1, ..., 9]
972 ...
973 ... >>> print range(10) # doctest: +ELLIPSIS
974 ... [0, 1, ..., 9]
975 ... '''
976 >>> test = doctest.DocTestFinder().find(f)[0]
977 >>> doctest.DocTestRunner(verbose=False).run(test)
978 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000979 Line 2, in f
980 Failed example:
981 print range(10) # should fail: no ellipsis
982 Expected:
983 [0, 1, ..., 9]
984 Got:
985 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +0000986 (1, 2)
987
988To turn an option off for an example, follow that example with a
989comment of the form ``# doctest: -OPTION``:
990
991 >>> def f(x): r'''
992 ... >>> print range(10)
993 ... [0, 1, ..., 9]
994 ...
995 ... >>> # should fail: no ellipsis
996 ... >>> print range(10) # doctest: -ELLIPSIS
997 ... [0, 1, ..., 9]
998 ... '''
999 >>> test = doctest.DocTestFinder().find(f)[0]
1000 >>> doctest.DocTestRunner(verbose=False,
1001 ... optionflags=doctest.ELLIPSIS).run(test)
1002 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001003 Line 6, in f
1004 Failed example:
1005 print range(10) # doctest: -ELLIPSIS
1006 Expected:
1007 [0, 1, ..., 9]
1008 Got:
1009 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001010 (1, 2)
1011
1012Option directives affect only the example that they appear with; they
1013do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001014
Edward Loper74bca7a2004-08-12 02:27:44 +00001015 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001016 ... >>> print range(10) # Should fail: no ellipsis
1017 ... [0, 1, ..., 9]
1018 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001019 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001020 ... [0, 1, ..., 9]
1021 ...
Tim Peters8485b562004-08-04 18:46:34 +00001022 ... >>> print range(10) # Should fail: no ellipsis
1023 ... [0, 1, ..., 9]
1024 ... '''
1025 >>> test = doctest.DocTestFinder().find(f)[0]
1026 >>> doctest.DocTestRunner(verbose=False).run(test)
1027 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001028 Line 2, in f
1029 Failed example:
1030 print range(10) # Should fail: no ellipsis
1031 Expected:
1032 [0, 1, ..., 9]
1033 Got:
1034 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001035 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001036 Line 8, in f
1037 Failed example:
1038 print range(10) # Should fail: no ellipsis
1039 Expected:
1040 [0, 1, ..., 9]
1041 Got:
1042 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001043 (2, 3)
1044
Edward Loper74bca7a2004-08-12 02:27:44 +00001045Multiple options may be modified by a single option directive. They
1046may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001047
1048 >>> def f(x): r'''
1049 ... >>> print range(10) # Should fail
1050 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001051 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001052 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001053 ... [0, 1, ..., 9]
1054 ... '''
1055 >>> test = doctest.DocTestFinder().find(f)[0]
1056 >>> doctest.DocTestRunner(verbose=False).run(test)
1057 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001058 Line 2, in f
1059 Failed example:
1060 print range(10) # Should fail
1061 Expected:
1062 [0, 1, ..., 9]
1063 Got:
1064 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001065 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001066
1067 >>> def f(x): r'''
1068 ... >>> print range(10) # Should fail
1069 ... [0, 1, ..., 9]
1070 ... >>> print range(10) # Should succeed
1071 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1072 ... [0, 1, ..., 9]
1073 ... '''
1074 >>> test = doctest.DocTestFinder().find(f)[0]
1075 >>> doctest.DocTestRunner(verbose=False).run(test)
1076 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001077 Line 2, in f
1078 Failed example:
1079 print range(10) # Should fail
1080 Expected:
1081 [0, 1, ..., 9]
1082 Got:
1083 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001084 (1, 2)
1085
1086 >>> def f(x): r'''
1087 ... >>> print range(10) # Should fail
1088 ... [0, 1, ..., 9]
1089 ... >>> print range(10) # Should succeed
1090 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1091 ... [0, 1, ..., 9]
1092 ... '''
1093 >>> test = doctest.DocTestFinder().find(f)[0]
1094 >>> doctest.DocTestRunner(verbose=False).run(test)
1095 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001096 Line 2, in f
1097 Failed example:
1098 print range(10) # Should fail
1099 Expected:
1100 [0, 1, ..., 9]
1101 Got:
1102 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001103 (1, 2)
1104
1105The option directive may be put on the line following the source, as
1106long as a continuation prompt is used:
1107
1108 >>> def f(x): r'''
1109 ... >>> print range(10)
1110 ... ... # doctest: +ELLIPSIS
1111 ... [0, 1, ..., 9]
1112 ... '''
1113 >>> test = doctest.DocTestFinder().find(f)[0]
1114 >>> doctest.DocTestRunner(verbose=False).run(test)
1115 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001116
Edward Loper74bca7a2004-08-12 02:27:44 +00001117For examples with multi-line source, the option directive may appear
1118at the end of any line:
1119
1120 >>> def f(x): r'''
1121 ... >>> for x in range(10): # doctest: +ELLIPSIS
1122 ... ... print x,
1123 ... 0 1 2 ... 9
1124 ...
1125 ... >>> for x in range(10):
1126 ... ... print x, # doctest: +ELLIPSIS
1127 ... 0 1 2 ... 9
1128 ... '''
1129 >>> test = doctest.DocTestFinder().find(f)[0]
1130 >>> doctest.DocTestRunner(verbose=False).run(test)
1131 (0, 2)
1132
1133If more than one line of an example with multi-line source has an
1134option directive, then they are combined:
1135
1136 >>> def f(x): r'''
1137 ... Should fail (option directive not on the last line):
1138 ... >>> for x in range(10): # doctest: +ELLIPSIS
1139 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1140 ... 0 1 2...9
1141 ... '''
1142 >>> test = doctest.DocTestFinder().find(f)[0]
1143 >>> doctest.DocTestRunner(verbose=False).run(test)
1144 (0, 1)
1145
1146It is an error to have a comment of the form ``# doctest:`` that is
1147*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1148``OPTION`` is an option that has been registered with
1149`register_option`:
1150
1151 >>> # Error: Option not registered
1152 >>> s = '>>> print 12 #doctest: +BADOPTION'
1153 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1154 Traceback (most recent call last):
1155 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1156
1157 >>> # Error: No + or - prefix
1158 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1159 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1160 Traceback (most recent call last):
1161 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1162
1163It is an error to use an option directive on a line that contains no
1164source:
1165
1166 >>> s = '>>> # doctest: +ELLIPSIS'
1167 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1168 Traceback (most recent call last):
1169 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 +00001170"""
1171
1172def test_testsource(): r"""
1173Unit tests for `testsource()`.
1174
1175The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001176test with that name in that module, and converts it to a script. The
1177example code is converted to regular Python code. The surrounding
1178words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001179
1180 >>> import test.test_doctest
1181 >>> name = 'test.test_doctest.sample_func'
1182 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001183 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001184 #
Tim Peters8485b562004-08-04 18:46:34 +00001185 print sample_func(22)
1186 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001187 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001188 #
Edward Lopera5db6002004-08-12 02:41:30 +00001189 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001190
1191 >>> name = 'test.test_doctest.SampleNewStyleClass'
1192 >>> print doctest.testsource(test.test_doctest, name)
1193 print '1\n2\n3'
1194 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001195 ## 1
1196 ## 2
1197 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001198
1199 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1200 >>> print doctest.testsource(test.test_doctest, name)
1201 print SampleClass.a_classmethod(10)
1202 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001203 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001204 print SampleClass(0).a_classmethod(10)
1205 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001206 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001207"""
1208
1209def test_debug(): r"""
1210
1211Create a docstring that we want to debug:
1212
1213 >>> s = '''
1214 ... >>> x = 12
1215 ... >>> print x
1216 ... 12
1217 ... '''
1218
1219Create some fake stdin input, to feed to the debugger:
1220
1221 >>> import tempfile
1222 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1223 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1224 >>> fake_stdin.seek(0)
1225 >>> real_stdin = sys.stdin
1226 >>> sys.stdin = fake_stdin
1227
1228Run the debugger on the docstring, and then restore sys.stdin.
1229
Tim Peters8485b562004-08-04 18:46:34 +00001230 >>> try:
1231 ... doctest.debug_src(s)
1232 ... finally:
1233 ... sys.stdin = real_stdin
1234 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001235 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001236 > <string>(1)?()
1237 (Pdb) 12
1238 --Return--
1239 > <string>(1)?()->None
1240 (Pdb) 12
1241 (Pdb)
1242
1243"""
1244
Jim Fulton356fd192004-08-09 11:34:47 +00001245def test_pdb_set_trace():
1246 r"""Using pdb.set_trace from a doctest
1247
Tim Peters413ced62004-08-09 15:43:47 +00001248 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001249 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001250 you use it. The doctest module changes sys.stdout so that it can
1251 capture program output. It also temporarily replaces pdb.set_trace
1252 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001253 see debugger output.
1254
1255 >>> doc = '''
1256 ... >>> x = 42
1257 ... >>> import pdb; pdb.set_trace()
1258 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001259 >>> parser = doctest.DocTestParser()
1260 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001261 >>> runner = doctest.DocTestRunner(verbose=False)
1262
1263 To demonstrate this, we'll create a fake standard input that
1264 captures our debugger input:
1265
1266 >>> import tempfile
1267 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1268 >>> fake_stdin.write('\n'.join([
1269 ... 'up', # up out of pdb.set_trace
1270 ... 'up', # up again to get out of our wrapper
1271 ... 'print x', # print data defined by the example
1272 ... 'continue', # stop debugging
1273 ... '']))
1274 >>> fake_stdin.seek(0)
1275 >>> real_stdin = sys.stdin
1276 >>> sys.stdin = fake_stdin
1277
Edward Loper74bca7a2004-08-12 02:27:44 +00001278 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001279 --Return--
1280 > ...set_trace()->None
1281 -> Pdb().set_trace()
1282 (Pdb) > ...set_trace()
1283 -> real_pdb_set_trace()
1284 (Pdb) > <string>(1)?()
1285 (Pdb) 42
1286 (Pdb) (0, 2)
1287
1288 >>> sys.stdin = real_stdin
1289 >>> fake_stdin.close()
1290
1291 You can also put pdb.set_trace in a function called from a test:
1292
1293 >>> def calls_set_trace():
1294 ... y=2
1295 ... import pdb; pdb.set_trace()
1296
1297 >>> doc = '''
1298 ... >>> x=1
1299 ... >>> calls_set_trace()
1300 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001301 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001302 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1303 >>> fake_stdin.write('\n'.join([
1304 ... 'up', # up out of pdb.set_trace
1305 ... 'up', # up again to get out of our wrapper
1306 ... 'print y', # print data defined in the function
1307 ... 'up', # out of function
1308 ... 'print x', # print data defined by the example
1309 ... 'continue', # stop debugging
1310 ... '']))
1311 >>> fake_stdin.seek(0)
1312 >>> real_stdin = sys.stdin
1313 >>> sys.stdin = fake_stdin
1314
Edward Loper74bca7a2004-08-12 02:27:44 +00001315 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001316 --Return--
1317 > ...set_trace()->None
1318 -> Pdb().set_trace()
1319 (Pdb) ...set_trace()
1320 -> real_pdb_set_trace()
1321 (Pdb) > <string>(3)calls_set_trace()
1322 (Pdb) 2
1323 (Pdb) > <string>(1)?()
1324 (Pdb) 1
1325 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001326 """
1327
Tim Peters19397e52004-08-06 22:02:59 +00001328def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001329 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001330
1331 We create a Suite by providing a module. A module can be provided
1332 by passing a module object:
1333
1334 >>> import unittest
1335 >>> import test.sample_doctest
1336 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1337 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001338 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001339
1340 We can also supply the module by name:
1341
1342 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1343 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001344 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001345
1346 We can use the current module:
1347
1348 >>> suite = test.sample_doctest.test_suite()
1349 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001350 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001351
1352 We can supply global variables. If we pass globs, they will be
1353 used instead of the module globals. Here we'll pass an empty
1354 globals, triggering an extra error:
1355
1356 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1357 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001358 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001359
1360 Alternatively, we can provide extra globals. Here we'll make an
1361 error go away by providing an extra global variable:
1362
1363 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1364 ... extraglobs={'y': 1})
1365 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001366 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001367
1368 You can pass option flags. Here we'll cause an extra error
1369 by disabling the blank-line feature:
1370
1371 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001372 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001373 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001374 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001375
Tim Peters1e277ee2004-08-07 05:37:52 +00001376 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001377
1378 >>> def setUp():
1379 ... import test.test_doctest
1380 ... test.test_doctest.sillySetup = True
1381
1382 >>> def tearDown():
1383 ... import test.test_doctest
1384 ... del test.test_doctest.sillySetup
1385
1386 Here, we installed a silly variable that the test expects:
1387
1388 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1389 ... setUp=setUp, tearDown=tearDown)
1390 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001391 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001392
1393 But the tearDown restores sanity:
1394
1395 >>> import test.test_doctest
1396 >>> test.test_doctest.sillySetup
1397 Traceback (most recent call last):
1398 ...
1399 AttributeError: 'module' object has no attribute 'sillySetup'
1400
1401 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001402 use a custom test_finder to to run just the test named bar.
1403 However, the test in the module docstring, and the two tests
1404 in the module __test__ dict, aren't filtered, so we actually
1405 run three tests besides bar's. The filtering mechanisms are
1406 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001407
1408 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001409 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001410 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1411 ... test_finder=finder)
1412 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001413 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001414 """
1415
1416def test_DocFileSuite():
1417 """We can test tests found in text files using a DocFileSuite.
1418
1419 We create a suite by providing the names of one or more text
1420 files that include examples:
1421
1422 >>> import unittest
1423 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1424 ... 'test_doctest2.txt')
1425 >>> suite.run(unittest.TestResult())
1426 <unittest.TestResult run=2 errors=0 failures=2>
1427
1428 The test files are looked for in the directory containing the
1429 calling module. A package keyword argument can be provided to
1430 specify a different relative location.
1431
1432 >>> import unittest
1433 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1434 ... 'test_doctest2.txt',
1435 ... package='test')
1436 >>> suite.run(unittest.TestResult())
1437 <unittest.TestResult run=2 errors=0 failures=2>
1438
1439 Note that '/' should be used as a path separator. It will be
1440 converted to a native separator at run time:
1441
1442
1443 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1444 >>> suite.run(unittest.TestResult())
1445 <unittest.TestResult run=1 errors=0 failures=1>
1446
1447 You can specify initial global variables:
1448
1449 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1450 ... 'test_doctest2.txt',
1451 ... globs={'favorite_color': 'blue'})
1452 >>> suite.run(unittest.TestResult())
1453 <unittest.TestResult run=2 errors=0 failures=1>
1454
1455 In this case, we supplied a missing favorite color. You can
1456 provide doctest options:
1457
1458 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1459 ... 'test_doctest2.txt',
1460 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1461 ... globs={'favorite_color': 'blue'})
1462 >>> suite.run(unittest.TestResult())
1463 <unittest.TestResult run=2 errors=0 failures=2>
1464
1465 And, you can provide setUp and tearDown functions:
1466
1467 You can supply setUp and teatDoen functions:
1468
1469 >>> def setUp():
1470 ... import test.test_doctest
1471 ... test.test_doctest.sillySetup = True
1472
1473 >>> def tearDown():
1474 ... import test.test_doctest
1475 ... del test.test_doctest.sillySetup
1476
1477 Here, we installed a silly variable that the test expects:
1478
1479 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1480 ... 'test_doctest2.txt',
1481 ... setUp=setUp, tearDown=tearDown)
1482 >>> suite.run(unittest.TestResult())
1483 <unittest.TestResult run=2 errors=0 failures=1>
1484
1485 But the tearDown restores sanity:
1486
1487 >>> import test.test_doctest
1488 >>> test.test_doctest.sillySetup
1489 Traceback (most recent call last):
1490 ...
1491 AttributeError: 'module' object has no attribute 'sillySetup'
1492
1493 """
1494
Jim Fulton07a349c2004-08-22 14:10:00 +00001495def test_trailing_space_in_test():
1496 """
Tim Petersa7def722004-08-23 22:13:22 +00001497 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001498
Jim Fulton07a349c2004-08-22 14:10:00 +00001499 >>> x, y = 'foo', ''
1500 >>> print x, y
1501 foo \n
1502 """
Tim Peters19397e52004-08-06 22:02:59 +00001503
Tim Petersa7def722004-08-23 22:13:22 +00001504# old_test1, ... used to live in doctest.py, but cluttered it. Note
1505# that these use the deprecated doctest.Tester, so should go away (or
1506# be rewritten) someday.
1507
1508# Ignore all warnings about the use of class Tester in this module.
1509# Note that the name of this module may differ depending on how it's
1510# imported, so the use of __name__ is important.
1511warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1512 __name__, 0)
1513
1514def old_test1(): r"""
1515>>> from doctest import Tester
1516>>> t = Tester(globs={'x': 42}, verbose=0)
1517>>> t.runstring(r'''
1518... >>> x = x * 2
1519... >>> print x
1520... 42
1521... ''', 'XYZ')
1522**********************************************************************
1523Line 3, in XYZ
1524Failed example:
1525 print x
1526Expected:
1527 42
1528Got:
1529 84
1530(1, 2)
1531>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1532(0, 2)
1533>>> t.summarize()
1534**********************************************************************
15351 items had failures:
1536 1 of 2 in XYZ
1537***Test Failed*** 1 failures.
1538(1, 4)
1539>>> t.summarize(verbose=1)
15401 items passed all tests:
1541 2 tests in example2
1542**********************************************************************
15431 items had failures:
1544 1 of 2 in XYZ
15454 tests in 2 items.
15463 passed and 1 failed.
1547***Test Failed*** 1 failures.
1548(1, 4)
1549"""
1550
1551def old_test2(): r"""
1552 >>> from doctest import Tester
1553 >>> t = Tester(globs={}, verbose=1)
1554 >>> test = r'''
1555 ... # just an example
1556 ... >>> x = 1 + 2
1557 ... >>> x
1558 ... 3
1559 ... '''
1560 >>> t.runstring(test, "Example")
1561 Running string Example
1562 Trying: x = 1 + 2
1563 Expecting: nothing
1564 ok
1565 Trying: x
1566 Expecting: 3
1567 ok
1568 0 of 2 examples failed in string Example
1569 (0, 2)
1570"""
1571
1572def old_test3(): r"""
1573 >>> from doctest import Tester
1574 >>> t = Tester(globs={}, verbose=0)
1575 >>> def _f():
1576 ... '''Trivial docstring example.
1577 ... >>> assert 2 == 2
1578 ... '''
1579 ... return 32
1580 ...
1581 >>> t.rundoc(_f) # expect 0 failures in 1 example
1582 (0, 1)
1583"""
1584
1585def old_test4(): """
1586 >>> import new
1587 >>> m1 = new.module('_m1')
1588 >>> m2 = new.module('_m2')
1589 >>> test_data = \"""
1590 ... def _f():
1591 ... '''>>> assert 1 == 1
1592 ... '''
1593 ... def g():
1594 ... '''>>> assert 2 != 1
1595 ... '''
1596 ... class H:
1597 ... '''>>> assert 2 > 1
1598 ... '''
1599 ... def bar(self):
1600 ... '''>>> assert 1 < 2
1601 ... '''
1602 ... \"""
1603 >>> exec test_data in m1.__dict__
1604 >>> exec test_data in m2.__dict__
1605 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
1606
1607 Tests that objects outside m1 are excluded:
1608
1609 >>> from doctest import Tester
1610 >>> t = Tester(globs={}, verbose=0)
1611 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
1612 (0, 4)
1613
1614 Once more, not excluding stuff outside m1:
1615
1616 >>> t = Tester(globs={}, verbose=0)
1617 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
1618 (0, 8)
1619
1620 The exclusion of objects from outside the designated module is
1621 meant to be invoked automagically by testmod.
1622
1623 >>> doctest.testmod(m1, verbose=False)
1624 (0, 4)
1625"""
1626
Tim Peters8485b562004-08-04 18:46:34 +00001627######################################################################
1628## Main
1629######################################################################
1630
1631def test_main():
1632 # Check the doctest cases in doctest itself:
1633 test_support.run_doctest(doctest, verbosity=True)
1634 # Check the doctest cases defined here:
1635 from test import test_doctest
1636 test_support.run_doctest(test_doctest, verbosity=True)
1637
1638import trace, sys, re, StringIO
1639def test_coverage(coverdir):
1640 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1641 trace=0, count=1)
1642 tracer.run('reload(doctest); test_main()')
1643 r = tracer.results()
1644 print 'Writing coverage results...'
1645 r.write_results(show_missing=True, summary=True,
1646 coverdir=coverdir)
1647
1648if __name__ == '__main__':
1649 if '-c' in sys.argv:
1650 test_coverage('/tmp/doctest.cover')
1651 else:
1652 test_main()