blob: d5e9ef50d45aa1f30f4239a8b12777d848cdecf6 [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
Tim Peters4de7c5c2004-08-23 22:38:05 +0000283The exact name depends on how test_doctest was invoked, so allow for
284leading path components.
285
286 >>> tests[0].filename # doctest: +ELLIPSIS
287 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000288
289 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000290
Jim Fulton07a349c2004-08-22 14:10:00 +0000291
Tim Peters8485b562004-08-04 18:46:34 +0000292 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000293 >>> (e.source, e.want, e.lineno)
294 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000295
Tim Peters8485b562004-08-04 18:46:34 +0000296If an object has no docstring, then a test is not created for it:
297
298 >>> def no_docstring(v):
299 ... pass
300 >>> finder.find(no_docstring)
301 []
302
303If the function has a docstring with no examples, then a test with no
304examples is returned. (This lets `DocTestRunner` collect statistics
305about which functions have no tests -- but is that useful? And should
306an empty test also be created when there's no docstring?)
307
308 >>> def no_examples(v):
309 ... ''' no doctest examples '''
310 >>> finder.find(no_examples)
311 [<DocTest no_examples from None:1 (no examples)>]
312
313Finding Tests in Classes
314~~~~~~~~~~~~~~~~~~~~~~~~
315For a class, DocTestFinder will create a test for the class's
316docstring, and will recursively explore its contents, including
317methods, classmethods, staticmethods, properties, and nested classes.
318
319 >>> finder = doctest.DocTestFinder()
320 >>> tests = finder.find(SampleClass)
321 >>> tests.sort()
322 >>> for t in tests:
323 ... print '%2s %s' % (len(t.examples), t.name)
324 1 SampleClass
325 3 SampleClass.NestedClass
326 1 SampleClass.NestedClass.__init__
327 1 SampleClass.__init__
328 2 SampleClass.a_classmethod
329 1 SampleClass.a_property
330 1 SampleClass.a_staticmethod
331 1 SampleClass.double
332 1 SampleClass.get
333
334New-style classes are also supported:
335
336 >>> tests = finder.find(SampleNewStyleClass)
337 >>> tests.sort()
338 >>> for t in tests:
339 ... print '%2s %s' % (len(t.examples), t.name)
340 1 SampleNewStyleClass
341 1 SampleNewStyleClass.__init__
342 1 SampleNewStyleClass.double
343 1 SampleNewStyleClass.get
344
345Finding Tests in Modules
346~~~~~~~~~~~~~~~~~~~~~~~~
347For a module, DocTestFinder will create a test for the class's
348docstring, and will recursively explore its contents, including
349functions, classes, and the `__test__` dictionary, if it exists:
350
351 >>> # A module
352 >>> import new
353 >>> m = new.module('some_module')
354 >>> def triple(val):
355 ... '''
356 ... >>> print tripple(11)
357 ... 33
358 ... '''
359 ... return val*3
360 >>> m.__dict__.update({
361 ... 'sample_func': sample_func,
362 ... 'SampleClass': SampleClass,
363 ... '__doc__': '''
364 ... Module docstring.
365 ... >>> print 'module'
366 ... module
367 ... ''',
368 ... '__test__': {
369 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
370 ... 'c': triple}})
371
372 >>> finder = doctest.DocTestFinder()
373 >>> # Use module=test.test_doctest, to prevent doctest from
374 >>> # ignoring the objects since they weren't defined in m.
375 >>> import test.test_doctest
376 >>> tests = finder.find(m, module=test.test_doctest)
377 >>> tests.sort()
378 >>> for t in tests:
379 ... print '%2s %s' % (len(t.examples), t.name)
380 1 some_module
381 1 some_module.SampleClass
382 3 some_module.SampleClass.NestedClass
383 1 some_module.SampleClass.NestedClass.__init__
384 1 some_module.SampleClass.__init__
385 2 some_module.SampleClass.a_classmethod
386 1 some_module.SampleClass.a_property
387 1 some_module.SampleClass.a_staticmethod
388 1 some_module.SampleClass.double
389 1 some_module.SampleClass.get
390 1 some_module.c
391 2 some_module.d
392 1 some_module.sample_func
393
394Duplicate Removal
395~~~~~~~~~~~~~~~~~
396If a single object is listed twice (under different names), then tests
397will only be generated for it once:
398
Tim Petersf3f57472004-08-08 06:11:48 +0000399 >>> from test import doctest_aliases
400 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000401 >>> tests.sort()
402 >>> print len(tests)
403 2
404 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000405 test.doctest_aliases.TwoNames
406
407 TwoNames.f and TwoNames.g are bound to the same object.
408 We can't guess which will be found in doctest's traversal of
409 TwoNames.__dict__ first, so we have to allow for either.
410
411 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000412 True
413
414Filter Functions
415~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000416A filter function can be used to restrict which objects get examined,
417but this is temporary, undocumented internal support for testmod's
418deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000419
420 >>> def namefilter(prefix, base):
421 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000422 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000423 >>> tests.sort()
424 >>> for t in tests:
425 ... print '%2s %s' % (len(t.examples), t.name)
426 1 SampleClass
427 3 SampleClass.NestedClass
428 1 SampleClass.NestedClass.__init__
429 1 SampleClass.__init__
430 1 SampleClass.double
431 1 SampleClass.get
432
Tim Peters8485b562004-08-04 18:46:34 +0000433If a given object is filtered out, then none of the objects that it
434contains will be added either:
435
436 >>> def namefilter(prefix, base):
437 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000438 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000439 >>> tests.sort()
440 >>> for t in tests:
441 ... print '%2s %s' % (len(t.examples), t.name)
442 1 SampleClass
443 1 SampleClass.__init__
444 2 SampleClass.a_classmethod
445 1 SampleClass.a_property
446 1 SampleClass.a_staticmethod
447 1 SampleClass.double
448 1 SampleClass.get
449
Tim Petersf727c6c2004-08-08 01:48:59 +0000450The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000451object explicitly passed to DocTestFinder:
452
453 >>> def namefilter(prefix, base):
454 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000455 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000456 >>> len(tests)
457 9
458
459Turning off Recursion
460~~~~~~~~~~~~~~~~~~~~~
461DocTestFinder can be told not to look for tests in contained objects
462using the `recurse` flag:
463
464 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
465 >>> tests.sort()
466 >>> for t in tests:
467 ... print '%2s %s' % (len(t.examples), t.name)
468 1 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000469
470Line numbers
471~~~~~~~~~~~~
472DocTestFinder finds the line number of each example:
473
474 >>> def f(x):
475 ... '''
476 ... >>> x = 12
477 ...
478 ... some text
479 ...
480 ... >>> # examples are not created for comments & bare prompts.
481 ... >>>
482 ... ...
483 ...
484 ... >>> for x in range(10):
485 ... ... print x,
486 ... 0 1 2 3 4 5 6 7 8 9
487 ... >>> x/2
488 ... 6
489 ... '''
490 >>> test = doctest.DocTestFinder().find(f)[0]
491 >>> [e.lineno for e in test.examples]
492 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000493"""
494
495class test_DocTestRunner:
496 def basics(): r"""
497Unit tests for the `DocTestRunner` class.
498
499DocTestRunner is used to run DocTest test cases, and to accumulate
500statistics. Here's a simple DocTest case we can use:
501
502 >>> def f(x):
503 ... '''
504 ... >>> x = 12
505 ... >>> print x
506 ... 12
507 ... >>> x/2
508 ... 6
509 ... '''
510 >>> test = doctest.DocTestFinder().find(f)[0]
511
512The main DocTestRunner interface is the `run` method, which runs a
513given DocTest case in a given namespace (globs). It returns a tuple
514`(f,t)`, where `f` is the number of failed tests and `t` is the number
515of tried tests.
516
517 >>> doctest.DocTestRunner(verbose=False).run(test)
518 (0, 3)
519
520If any example produces incorrect output, then the test runner reports
521the failure and proceeds to the next example:
522
523 >>> def f(x):
524 ... '''
525 ... >>> x = 12
526 ... >>> print x
527 ... 14
528 ... >>> x/2
529 ... 6
530 ... '''
531 >>> test = doctest.DocTestFinder().find(f)[0]
532 >>> doctest.DocTestRunner(verbose=True).run(test)
533 Trying: x = 12
534 Expecting: nothing
535 ok
536 Trying: print x
537 Expecting: 14
538 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000539 Line 3, in f
540 Failed example:
541 print x
542 Expected:
543 14
544 Got:
545 12
Tim Peters8485b562004-08-04 18:46:34 +0000546 Trying: x/2
547 Expecting: 6
548 ok
549 (1, 3)
550"""
551 def verbose_flag(): r"""
552The `verbose` flag makes the test runner generate more detailed
553output:
554
555 >>> def f(x):
556 ... '''
557 ... >>> x = 12
558 ... >>> print x
559 ... 12
560 ... >>> x/2
561 ... 6
562 ... '''
563 >>> test = doctest.DocTestFinder().find(f)[0]
564
565 >>> doctest.DocTestRunner(verbose=True).run(test)
566 Trying: x = 12
567 Expecting: nothing
568 ok
569 Trying: print x
570 Expecting: 12
571 ok
572 Trying: x/2
573 Expecting: 6
574 ok
575 (0, 3)
576
577If the `verbose` flag is unspecified, then the output will be verbose
578iff `-v` appears in sys.argv:
579
580 >>> # Save the real sys.argv list.
581 >>> old_argv = sys.argv
582
583 >>> # If -v does not appear in sys.argv, then output isn't verbose.
584 >>> sys.argv = ['test']
585 >>> doctest.DocTestRunner().run(test)
586 (0, 3)
587
588 >>> # If -v does appear in sys.argv, then output is verbose.
589 >>> sys.argv = ['test', '-v']
590 >>> doctest.DocTestRunner().run(test)
591 Trying: x = 12
592 Expecting: nothing
593 ok
594 Trying: print x
595 Expecting: 12
596 ok
597 Trying: x/2
598 Expecting: 6
599 ok
600 (0, 3)
601
602 >>> # Restore sys.argv
603 >>> sys.argv = old_argv
604
605In the remaining examples, the test runner's verbosity will be
606explicitly set, to ensure that the test behavior is consistent.
607 """
608 def exceptions(): r"""
609Tests of `DocTestRunner`'s exception handling.
610
611An expected exception is specified with a traceback message. The
612lines between the first line and the type/value may be omitted or
613replaced with any other string:
614
615 >>> def f(x):
616 ... '''
617 ... >>> x = 12
618 ... >>> print x/0
619 ... Traceback (most recent call last):
620 ... ZeroDivisionError: integer division or modulo by zero
621 ... '''
622 >>> test = doctest.DocTestFinder().find(f)[0]
623 >>> doctest.DocTestRunner(verbose=False).run(test)
624 (0, 2)
625
626An example may generate output before it raises an exception; if it
627does, then the output must match the expected output:
628
629 >>> def f(x):
630 ... '''
631 ... >>> x = 12
632 ... >>> print 'pre-exception output', x/0
633 ... pre-exception output
634 ... Traceback (most recent call last):
635 ... ZeroDivisionError: integer division or modulo by zero
636 ... '''
637 >>> test = doctest.DocTestFinder().find(f)[0]
638 >>> doctest.DocTestRunner(verbose=False).run(test)
639 (0, 2)
640
641Exception messages may contain newlines:
642
643 >>> def f(x):
644 ... r'''
645 ... >>> raise ValueError, 'multi\nline\nmessage'
646 ... Traceback (most recent call last):
647 ... ValueError: multi
648 ... line
649 ... message
650 ... '''
651 >>> test = doctest.DocTestFinder().find(f)[0]
652 >>> doctest.DocTestRunner(verbose=False).run(test)
653 (0, 1)
654
655If an exception is expected, but an exception with the wrong type or
656message is raised, then it is reported as a failure:
657
658 >>> def f(x):
659 ... r'''
660 ... >>> raise ValueError, 'message'
661 ... Traceback (most recent call last):
662 ... ValueError: wrong message
663 ... '''
664 >>> test = doctest.DocTestFinder().find(f)[0]
665 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000666 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000667 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000668 Line 2, in f
669 Failed example:
670 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000671 Expected:
672 Traceback (most recent call last):
673 ValueError: wrong message
674 Got:
675 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000676 ...
Tim Peters8485b562004-08-04 18:46:34 +0000677 ValueError: message
678 (1, 1)
679
680If an exception is raised but not expected, then it is reported as an
681unexpected exception:
682
Tim Peters8485b562004-08-04 18:46:34 +0000683 >>> def f(x):
684 ... r'''
685 ... >>> 1/0
686 ... 0
687 ... '''
688 >>> test = doctest.DocTestFinder().find(f)[0]
689 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000690 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000691 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000692 Line 2, in f
693 Failed example:
694 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000695 Exception raised:
696 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000697 ...
Tim Peters8485b562004-08-04 18:46:34 +0000698 ZeroDivisionError: integer division or modulo by zero
699 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000700"""
701 def optionflags(): r"""
702Tests of `DocTestRunner`'s option flag handling.
703
704Several option flags can be used to customize the behavior of the test
705runner. These are defined as module constants in doctest, and passed
706to the DocTestRunner constructor (multiple constants should be or-ed
707together).
708
709The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
710and 1/0:
711
712 >>> def f(x):
713 ... '>>> True\n1\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_TRUE_FOR_1
723 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
724 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000725 Line 1, in f
726 Failed example:
727 True
728 Expected:
729 1
730 Got:
731 True
Tim Peters8485b562004-08-04 18:46:34 +0000732 (1, 1)
733
734The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
735and the '<BLANKLINE>' marker:
736
737 >>> def f(x):
738 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
739
740 >>> # Without the flag:
741 >>> test = doctest.DocTestFinder().find(f)[0]
742 >>> doctest.DocTestRunner(verbose=False).run(test)
743 (0, 1)
744
745 >>> # With the flag:
746 >>> test = doctest.DocTestFinder().find(f)[0]
747 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
748 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
749 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000750 Line 1, in f
751 Failed example:
752 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000753 Expected:
754 a
755 <BLANKLINE>
756 b
757 Got:
758 a
759 <BLANKLINE>
760 b
761 (1, 1)
762
763The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
764treated as equal:
765
766 >>> def f(x):
767 ... '>>> print 1, 2, 3\n 1 2\n 3'
768
769 >>> # Without the flag:
770 >>> test = doctest.DocTestFinder().find(f)[0]
771 >>> doctest.DocTestRunner(verbose=False).run(test)
772 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000773 Line 1, in f
774 Failed example:
775 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000776 Expected:
777 1 2
778 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000779 Got:
780 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000781 (1, 1)
782
783 >>> # With the flag:
784 >>> test = doctest.DocTestFinder().find(f)[0]
785 >>> flags = doctest.NORMALIZE_WHITESPACE
786 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
787 (0, 1)
788
Tim Peters026f8dc2004-08-19 16:38:58 +0000789 An example from the docs:
790 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
791 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
792 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
793
Tim Peters8485b562004-08-04 18:46:34 +0000794The ELLIPSIS flag causes ellipsis marker ("...") in the expected
795output to match any substring in the actual output:
796
797 >>> def f(x):
798 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
799
800 >>> # Without the flag:
801 >>> test = doctest.DocTestFinder().find(f)[0]
802 >>> doctest.DocTestRunner(verbose=False).run(test)
803 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000804 Line 1, in f
805 Failed example:
806 print range(15)
807 Expected:
808 [0, 1, 2, ..., 14]
809 Got:
810 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +0000811 (1, 1)
812
813 >>> # With the flag:
814 >>> test = doctest.DocTestFinder().find(f)[0]
815 >>> flags = doctest.ELLIPSIS
816 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
817 (0, 1)
818
Tim Peterse594bee2004-08-22 01:47:51 +0000819 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +0000820
821 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +0000822 ... print i**2, #doctest: +ELLIPSIS
823 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +0000824
Tim Peters026f8dc2004-08-19 16:38:58 +0000825 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000826
827 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +0000828 ... print i,
829 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +0000830
Tim Peters026f8dc2004-08-19 16:38:58 +0000831 Examples from the docs:
832
833 >>> print range(20) # doctest:+ELLIPSIS
834 [0, 1, ..., 18, 19]
835
836 >>> print range(20) # doctest: +ELLIPSIS
837 ... # doctest: +NORMALIZE_WHITESPACE
838 [0, 1, ..., 18, 19]
839
Tim Peters8485b562004-08-04 18:46:34 +0000840The UNIFIED_DIFF flag causes failures that involve multi-line expected
841and actual outputs to be displayed using a unified diff:
842
843 >>> def f(x):
844 ... r'''
845 ... >>> print '\n'.join('abcdefg')
846 ... a
847 ... B
848 ... c
849 ... d
850 ... f
851 ... g
852 ... h
853 ... '''
854
855 >>> # Without the flag:
856 >>> test = doctest.DocTestFinder().find(f)[0]
857 >>> doctest.DocTestRunner(verbose=False).run(test)
858 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000859 Line 2, in f
860 Failed example:
861 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000862 Expected:
863 a
864 B
865 c
866 d
867 f
868 g
869 h
870 Got:
871 a
872 b
873 c
874 d
875 e
876 f
877 g
878 (1, 1)
879
880 >>> # With the flag:
881 >>> test = doctest.DocTestFinder().find(f)[0]
882 >>> flags = doctest.UNIFIED_DIFF
883 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
884 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000885 Line 2, in f
886 Failed example:
887 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000888 Differences (unified diff):
889 --- Expected
890 +++ Got
891 @@ -1,8 +1,8 @@
892 a
893 -B
894 +b
895 c
896 d
897 +e
898 f
899 g
900 -h
901 <BLANKLINE>
902 (1, 1)
903
904The CONTEXT_DIFF flag causes failures that involve multi-line expected
905and actual outputs to be displayed using a context diff:
906
907 >>> # Reuse f() from the UNIFIED_DIFF example, above.
908 >>> test = doctest.DocTestFinder().find(f)[0]
909 >>> flags = doctest.CONTEXT_DIFF
910 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
911 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000912 Line 2, in f
913 Failed example:
914 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000915 Differences (context diff):
916 *** Expected
917 --- Got
918 ***************
919 *** 1,8 ****
920 a
921 ! B
922 c
923 d
924 f
925 g
926 - h
927 <BLANKLINE>
928 --- 1,8 ----
929 a
930 ! b
931 c
932 d
933 + e
934 f
935 g
936 <BLANKLINE>
937 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +0000938
939
940The NDIFF_DIFF flag causes failures to use the difflib.Differ algorithm
941used by the popular ndiff.py utility. This does intraline difference
942marking, as well as interline differences.
943
944 >>> def f(x):
945 ... r'''
946 ... >>> print "a b c d e f g h i j k l m"
947 ... a b c d e f g h i j k 1 m
948 ... '''
949 >>> test = doctest.DocTestFinder().find(f)[0]
950 >>> flags = doctest.NDIFF_DIFF
951 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
952 **********************************************************************
953 Line 2, in f
954 Failed example:
955 print "a b c d e f g h i j k l m"
956 Differences (ndiff with -expected +actual):
957 - a b c d e f g h i j k 1 m
958 ? ^
959 + a b c d e f g h i j k l m
960 ? + ++ ^
961 <BLANKLINE>
962 (1, 1)
963 """
964
Tim Peters8485b562004-08-04 18:46:34 +0000965 def option_directives(): r"""
966Tests of `DocTestRunner`'s option directive mechanism.
967
Edward Loper74bca7a2004-08-12 02:27:44 +0000968Option directives can be used to turn option flags on or off for a
969single example. To turn an option on for an example, follow that
970example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +0000971
972 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +0000973 ... >>> print range(10) # should fail: no ellipsis
974 ... [0, 1, ..., 9]
975 ...
976 ... >>> print range(10) # doctest: +ELLIPSIS
977 ... [0, 1, ..., 9]
978 ... '''
979 >>> test = doctest.DocTestFinder().find(f)[0]
980 >>> doctest.DocTestRunner(verbose=False).run(test)
981 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000982 Line 2, in f
983 Failed example:
984 print range(10) # should fail: no ellipsis
985 Expected:
986 [0, 1, ..., 9]
987 Got:
988 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +0000989 (1, 2)
990
991To turn an option off for an example, follow that example with a
992comment of the form ``# doctest: -OPTION``:
993
994 >>> def f(x): r'''
995 ... >>> print range(10)
996 ... [0, 1, ..., 9]
997 ...
998 ... >>> # should fail: no ellipsis
999 ... >>> print range(10) # doctest: -ELLIPSIS
1000 ... [0, 1, ..., 9]
1001 ... '''
1002 >>> test = doctest.DocTestFinder().find(f)[0]
1003 >>> doctest.DocTestRunner(verbose=False,
1004 ... optionflags=doctest.ELLIPSIS).run(test)
1005 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001006 Line 6, in f
1007 Failed example:
1008 print range(10) # doctest: -ELLIPSIS
1009 Expected:
1010 [0, 1, ..., 9]
1011 Got:
1012 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001013 (1, 2)
1014
1015Option directives affect only the example that they appear with; they
1016do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001017
Edward Loper74bca7a2004-08-12 02:27:44 +00001018 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001019 ... >>> print range(10) # Should fail: no ellipsis
1020 ... [0, 1, ..., 9]
1021 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001022 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001023 ... [0, 1, ..., 9]
1024 ...
Tim Peters8485b562004-08-04 18:46:34 +00001025 ... >>> print range(10) # Should fail: no ellipsis
1026 ... [0, 1, ..., 9]
1027 ... '''
1028 >>> test = doctest.DocTestFinder().find(f)[0]
1029 >>> doctest.DocTestRunner(verbose=False).run(test)
1030 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001031 Line 2, in f
1032 Failed example:
1033 print range(10) # Should fail: no ellipsis
1034 Expected:
1035 [0, 1, ..., 9]
1036 Got:
1037 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001038 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001039 Line 8, in f
1040 Failed example:
1041 print range(10) # Should fail: no ellipsis
1042 Expected:
1043 [0, 1, ..., 9]
1044 Got:
1045 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001046 (2, 3)
1047
Edward Loper74bca7a2004-08-12 02:27:44 +00001048Multiple options may be modified by a single option directive. They
1049may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001050
1051 >>> def f(x): r'''
1052 ... >>> print range(10) # Should fail
1053 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001054 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001055 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001056 ... [0, 1, ..., 9]
1057 ... '''
1058 >>> test = doctest.DocTestFinder().find(f)[0]
1059 >>> doctest.DocTestRunner(verbose=False).run(test)
1060 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001061 Line 2, in f
1062 Failed example:
1063 print range(10) # Should fail
1064 Expected:
1065 [0, 1, ..., 9]
1066 Got:
1067 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001068 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001069
1070 >>> def f(x): r'''
1071 ... >>> print range(10) # Should fail
1072 ... [0, 1, ..., 9]
1073 ... >>> print range(10) # Should succeed
1074 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1075 ... [0, 1, ..., 9]
1076 ... '''
1077 >>> test = doctest.DocTestFinder().find(f)[0]
1078 >>> doctest.DocTestRunner(verbose=False).run(test)
1079 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001080 Line 2, in f
1081 Failed example:
1082 print range(10) # Should fail
1083 Expected:
1084 [0, 1, ..., 9]
1085 Got:
1086 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001087 (1, 2)
1088
1089 >>> def f(x): r'''
1090 ... >>> print range(10) # Should fail
1091 ... [0, 1, ..., 9]
1092 ... >>> print range(10) # Should succeed
1093 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1094 ... [0, 1, ..., 9]
1095 ... '''
1096 >>> test = doctest.DocTestFinder().find(f)[0]
1097 >>> doctest.DocTestRunner(verbose=False).run(test)
1098 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001099 Line 2, in f
1100 Failed example:
1101 print range(10) # Should fail
1102 Expected:
1103 [0, 1, ..., 9]
1104 Got:
1105 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001106 (1, 2)
1107
1108The option directive may be put on the line following the source, as
1109long as a continuation prompt is used:
1110
1111 >>> def f(x): r'''
1112 ... >>> print range(10)
1113 ... ... # doctest: +ELLIPSIS
1114 ... [0, 1, ..., 9]
1115 ... '''
1116 >>> test = doctest.DocTestFinder().find(f)[0]
1117 >>> doctest.DocTestRunner(verbose=False).run(test)
1118 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001119
Edward Loper74bca7a2004-08-12 02:27:44 +00001120For examples with multi-line source, the option directive may appear
1121at the end of any line:
1122
1123 >>> def f(x): r'''
1124 ... >>> for x in range(10): # doctest: +ELLIPSIS
1125 ... ... print x,
1126 ... 0 1 2 ... 9
1127 ...
1128 ... >>> for x in range(10):
1129 ... ... print x, # doctest: +ELLIPSIS
1130 ... 0 1 2 ... 9
1131 ... '''
1132 >>> test = doctest.DocTestFinder().find(f)[0]
1133 >>> doctest.DocTestRunner(verbose=False).run(test)
1134 (0, 2)
1135
1136If more than one line of an example with multi-line source has an
1137option directive, then they are combined:
1138
1139 >>> def f(x): r'''
1140 ... Should fail (option directive not on the last line):
1141 ... >>> for x in range(10): # doctest: +ELLIPSIS
1142 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1143 ... 0 1 2...9
1144 ... '''
1145 >>> test = doctest.DocTestFinder().find(f)[0]
1146 >>> doctest.DocTestRunner(verbose=False).run(test)
1147 (0, 1)
1148
1149It is an error to have a comment of the form ``# doctest:`` that is
1150*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1151``OPTION`` is an option that has been registered with
1152`register_option`:
1153
1154 >>> # Error: Option not registered
1155 >>> s = '>>> print 12 #doctest: +BADOPTION'
1156 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1157 Traceback (most recent call last):
1158 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1159
1160 >>> # Error: No + or - prefix
1161 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1162 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1163 Traceback (most recent call last):
1164 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1165
1166It is an error to use an option directive on a line that contains no
1167source:
1168
1169 >>> s = '>>> # doctest: +ELLIPSIS'
1170 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1171 Traceback (most recent call last):
1172 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 +00001173"""
1174
1175def test_testsource(): r"""
1176Unit tests for `testsource()`.
1177
1178The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001179test with that name in that module, and converts it to a script. The
1180example code is converted to regular Python code. The surrounding
1181words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001182
1183 >>> import test.test_doctest
1184 >>> name = 'test.test_doctest.sample_func'
1185 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001186 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001187 #
Tim Peters8485b562004-08-04 18:46:34 +00001188 print sample_func(22)
1189 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001190 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001191 #
Edward Lopera5db6002004-08-12 02:41:30 +00001192 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001193
1194 >>> name = 'test.test_doctest.SampleNewStyleClass'
1195 >>> print doctest.testsource(test.test_doctest, name)
1196 print '1\n2\n3'
1197 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001198 ## 1
1199 ## 2
1200 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001201
1202 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1203 >>> print doctest.testsource(test.test_doctest, name)
1204 print SampleClass.a_classmethod(10)
1205 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001206 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001207 print SampleClass(0).a_classmethod(10)
1208 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001209 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001210"""
1211
1212def test_debug(): r"""
1213
1214Create a docstring that we want to debug:
1215
1216 >>> s = '''
1217 ... >>> x = 12
1218 ... >>> print x
1219 ... 12
1220 ... '''
1221
1222Create some fake stdin input, to feed to the debugger:
1223
1224 >>> import tempfile
1225 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1226 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1227 >>> fake_stdin.seek(0)
1228 >>> real_stdin = sys.stdin
1229 >>> sys.stdin = fake_stdin
1230
1231Run the debugger on the docstring, and then restore sys.stdin.
1232
Tim Peters8485b562004-08-04 18:46:34 +00001233 >>> try:
1234 ... doctest.debug_src(s)
1235 ... finally:
1236 ... sys.stdin = real_stdin
1237 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001238 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001239 > <string>(1)?()
1240 (Pdb) 12
1241 --Return--
1242 > <string>(1)?()->None
1243 (Pdb) 12
1244 (Pdb)
1245
1246"""
1247
Jim Fulton356fd192004-08-09 11:34:47 +00001248def test_pdb_set_trace():
1249 r"""Using pdb.set_trace from a doctest
1250
Tim Peters413ced62004-08-09 15:43:47 +00001251 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001252 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001253 you use it. The doctest module changes sys.stdout so that it can
1254 capture program output. It also temporarily replaces pdb.set_trace
1255 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001256 see debugger output.
1257
1258 >>> doc = '''
1259 ... >>> x = 42
1260 ... >>> import pdb; pdb.set_trace()
1261 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001262 >>> parser = doctest.DocTestParser()
1263 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001264 >>> runner = doctest.DocTestRunner(verbose=False)
1265
1266 To demonstrate this, we'll create a fake standard input that
1267 captures our debugger input:
1268
1269 >>> import tempfile
1270 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1271 >>> fake_stdin.write('\n'.join([
1272 ... 'up', # up out of pdb.set_trace
1273 ... 'up', # up again to get out of our wrapper
1274 ... 'print x', # print data defined by the example
1275 ... 'continue', # stop debugging
1276 ... '']))
1277 >>> fake_stdin.seek(0)
1278 >>> real_stdin = sys.stdin
1279 >>> sys.stdin = fake_stdin
1280
Edward Loper74bca7a2004-08-12 02:27:44 +00001281 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001282 --Return--
1283 > ...set_trace()->None
1284 -> Pdb().set_trace()
1285 (Pdb) > ...set_trace()
1286 -> real_pdb_set_trace()
1287 (Pdb) > <string>(1)?()
1288 (Pdb) 42
1289 (Pdb) (0, 2)
1290
1291 >>> sys.stdin = real_stdin
1292 >>> fake_stdin.close()
1293
1294 You can also put pdb.set_trace in a function called from a test:
1295
1296 >>> def calls_set_trace():
1297 ... y=2
1298 ... import pdb; pdb.set_trace()
1299
1300 >>> doc = '''
1301 ... >>> x=1
1302 ... >>> calls_set_trace()
1303 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001304 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001305 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1306 >>> fake_stdin.write('\n'.join([
1307 ... 'up', # up out of pdb.set_trace
1308 ... 'up', # up again to get out of our wrapper
1309 ... 'print y', # print data defined in the function
1310 ... 'up', # out of function
1311 ... 'print x', # print data defined by the example
1312 ... 'continue', # stop debugging
1313 ... '']))
1314 >>> fake_stdin.seek(0)
1315 >>> real_stdin = sys.stdin
1316 >>> sys.stdin = fake_stdin
1317
Edward Loper74bca7a2004-08-12 02:27:44 +00001318 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001319 --Return--
1320 > ...set_trace()->None
1321 -> Pdb().set_trace()
1322 (Pdb) ...set_trace()
1323 -> real_pdb_set_trace()
1324 (Pdb) > <string>(3)calls_set_trace()
1325 (Pdb) 2
1326 (Pdb) > <string>(1)?()
1327 (Pdb) 1
1328 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001329 """
1330
Tim Peters19397e52004-08-06 22:02:59 +00001331def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001332 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001333
1334 We create a Suite by providing a module. A module can be provided
1335 by passing a module object:
1336
1337 >>> import unittest
1338 >>> import test.sample_doctest
1339 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1340 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001341 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001342
1343 We can also supply the module by name:
1344
1345 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1346 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001347 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001348
1349 We can use the current module:
1350
1351 >>> suite = test.sample_doctest.test_suite()
1352 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001353 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001354
1355 We can supply global variables. If we pass globs, they will be
1356 used instead of the module globals. Here we'll pass an empty
1357 globals, triggering an extra error:
1358
1359 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1360 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001361 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001362
1363 Alternatively, we can provide extra globals. Here we'll make an
1364 error go away by providing an extra global variable:
1365
1366 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1367 ... extraglobs={'y': 1})
1368 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001369 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001370
1371 You can pass option flags. Here we'll cause an extra error
1372 by disabling the blank-line feature:
1373
1374 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001375 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001376 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001377 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001378
Tim Peters1e277ee2004-08-07 05:37:52 +00001379 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001380
1381 >>> def setUp():
1382 ... import test.test_doctest
1383 ... test.test_doctest.sillySetup = True
1384
1385 >>> def tearDown():
1386 ... import test.test_doctest
1387 ... del test.test_doctest.sillySetup
1388
1389 Here, we installed a silly variable that the test expects:
1390
1391 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1392 ... setUp=setUp, tearDown=tearDown)
1393 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001394 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001395
1396 But the tearDown restores sanity:
1397
1398 >>> import test.test_doctest
1399 >>> test.test_doctest.sillySetup
1400 Traceback (most recent call last):
1401 ...
1402 AttributeError: 'module' object has no attribute 'sillySetup'
1403
1404 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001405 use a custom test_finder to to run just the test named bar.
1406 However, the test in the module docstring, and the two tests
1407 in the module __test__ dict, aren't filtered, so we actually
1408 run three tests besides bar's. The filtering mechanisms are
1409 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001410
1411 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001412 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001413 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1414 ... test_finder=finder)
1415 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001416 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001417 """
1418
1419def test_DocFileSuite():
1420 """We can test tests found in text files using a DocFileSuite.
1421
1422 We create a suite by providing the names of one or more text
1423 files that include examples:
1424
1425 >>> import unittest
1426 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1427 ... 'test_doctest2.txt')
1428 >>> suite.run(unittest.TestResult())
1429 <unittest.TestResult run=2 errors=0 failures=2>
1430
1431 The test files are looked for in the directory containing the
1432 calling module. A package keyword argument can be provided to
1433 specify a different relative location.
1434
1435 >>> import unittest
1436 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1437 ... 'test_doctest2.txt',
1438 ... package='test')
1439 >>> suite.run(unittest.TestResult())
1440 <unittest.TestResult run=2 errors=0 failures=2>
1441
1442 Note that '/' should be used as a path separator. It will be
1443 converted to a native separator at run time:
1444
1445
1446 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1447 >>> suite.run(unittest.TestResult())
1448 <unittest.TestResult run=1 errors=0 failures=1>
1449
1450 You can specify initial global variables:
1451
1452 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1453 ... 'test_doctest2.txt',
1454 ... globs={'favorite_color': 'blue'})
1455 >>> suite.run(unittest.TestResult())
1456 <unittest.TestResult run=2 errors=0 failures=1>
1457
1458 In this case, we supplied a missing favorite color. You can
1459 provide doctest options:
1460
1461 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1462 ... 'test_doctest2.txt',
1463 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1464 ... globs={'favorite_color': 'blue'})
1465 >>> suite.run(unittest.TestResult())
1466 <unittest.TestResult run=2 errors=0 failures=2>
1467
1468 And, you can provide setUp and tearDown functions:
1469
1470 You can supply setUp and teatDoen functions:
1471
1472 >>> def setUp():
1473 ... import test.test_doctest
1474 ... test.test_doctest.sillySetup = True
1475
1476 >>> def tearDown():
1477 ... import test.test_doctest
1478 ... del test.test_doctest.sillySetup
1479
1480 Here, we installed a silly variable that the test expects:
1481
1482 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1483 ... 'test_doctest2.txt',
1484 ... setUp=setUp, tearDown=tearDown)
1485 >>> suite.run(unittest.TestResult())
1486 <unittest.TestResult run=2 errors=0 failures=1>
1487
1488 But the tearDown restores sanity:
1489
1490 >>> import test.test_doctest
1491 >>> test.test_doctest.sillySetup
1492 Traceback (most recent call last):
1493 ...
1494 AttributeError: 'module' object has no attribute 'sillySetup'
1495
1496 """
1497
Jim Fulton07a349c2004-08-22 14:10:00 +00001498def test_trailing_space_in_test():
1499 """
Tim Petersa7def722004-08-23 22:13:22 +00001500 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001501
Jim Fulton07a349c2004-08-22 14:10:00 +00001502 >>> x, y = 'foo', ''
1503 >>> print x, y
1504 foo \n
1505 """
Tim Peters19397e52004-08-06 22:02:59 +00001506
Tim Petersa7def722004-08-23 22:13:22 +00001507# old_test1, ... used to live in doctest.py, but cluttered it. Note
1508# that these use the deprecated doctest.Tester, so should go away (or
1509# be rewritten) someday.
1510
1511# Ignore all warnings about the use of class Tester in this module.
1512# Note that the name of this module may differ depending on how it's
1513# imported, so the use of __name__ is important.
1514warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1515 __name__, 0)
1516
1517def old_test1(): r"""
1518>>> from doctest import Tester
1519>>> t = Tester(globs={'x': 42}, verbose=0)
1520>>> t.runstring(r'''
1521... >>> x = x * 2
1522... >>> print x
1523... 42
1524... ''', 'XYZ')
1525**********************************************************************
1526Line 3, in XYZ
1527Failed example:
1528 print x
1529Expected:
1530 42
1531Got:
1532 84
1533(1, 2)
1534>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1535(0, 2)
1536>>> t.summarize()
1537**********************************************************************
15381 items had failures:
1539 1 of 2 in XYZ
1540***Test Failed*** 1 failures.
1541(1, 4)
1542>>> t.summarize(verbose=1)
15431 items passed all tests:
1544 2 tests in example2
1545**********************************************************************
15461 items had failures:
1547 1 of 2 in XYZ
15484 tests in 2 items.
15493 passed and 1 failed.
1550***Test Failed*** 1 failures.
1551(1, 4)
1552"""
1553
1554def old_test2(): r"""
1555 >>> from doctest import Tester
1556 >>> t = Tester(globs={}, verbose=1)
1557 >>> test = r'''
1558 ... # just an example
1559 ... >>> x = 1 + 2
1560 ... >>> x
1561 ... 3
1562 ... '''
1563 >>> t.runstring(test, "Example")
1564 Running string Example
1565 Trying: x = 1 + 2
1566 Expecting: nothing
1567 ok
1568 Trying: x
1569 Expecting: 3
1570 ok
1571 0 of 2 examples failed in string Example
1572 (0, 2)
1573"""
1574
1575def old_test3(): r"""
1576 >>> from doctest import Tester
1577 >>> t = Tester(globs={}, verbose=0)
1578 >>> def _f():
1579 ... '''Trivial docstring example.
1580 ... >>> assert 2 == 2
1581 ... '''
1582 ... return 32
1583 ...
1584 >>> t.rundoc(_f) # expect 0 failures in 1 example
1585 (0, 1)
1586"""
1587
1588def old_test4(): """
1589 >>> import new
1590 >>> m1 = new.module('_m1')
1591 >>> m2 = new.module('_m2')
1592 >>> test_data = \"""
1593 ... def _f():
1594 ... '''>>> assert 1 == 1
1595 ... '''
1596 ... def g():
1597 ... '''>>> assert 2 != 1
1598 ... '''
1599 ... class H:
1600 ... '''>>> assert 2 > 1
1601 ... '''
1602 ... def bar(self):
1603 ... '''>>> assert 1 < 2
1604 ... '''
1605 ... \"""
1606 >>> exec test_data in m1.__dict__
1607 >>> exec test_data in m2.__dict__
1608 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
1609
1610 Tests that objects outside m1 are excluded:
1611
1612 >>> from doctest import Tester
1613 >>> t = Tester(globs={}, verbose=0)
1614 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
1615 (0, 4)
1616
1617 Once more, not excluding stuff outside m1:
1618
1619 >>> t = Tester(globs={}, verbose=0)
1620 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
1621 (0, 8)
1622
1623 The exclusion of objects from outside the designated module is
1624 meant to be invoked automagically by testmod.
1625
1626 >>> doctest.testmod(m1, verbose=False)
1627 (0, 4)
1628"""
1629
Tim Peters8485b562004-08-04 18:46:34 +00001630######################################################################
1631## Main
1632######################################################################
1633
1634def test_main():
1635 # Check the doctest cases in doctest itself:
1636 test_support.run_doctest(doctest, verbosity=True)
1637 # Check the doctest cases defined here:
1638 from test import test_doctest
1639 test_support.run_doctest(test_doctest, verbosity=True)
1640
1641import trace, sys, re, StringIO
1642def test_coverage(coverdir):
1643 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1644 trace=0, count=1)
1645 tracer.run('reload(doctest); test_main()')
1646 r = tracer.results()
1647 print 'Writing coverage results...'
1648 r.write_results(show_missing=True, summary=True,
1649 coverdir=coverdir)
1650
1651if __name__ == '__main__':
1652 if '-c' in sys.argv:
1653 test_coverage('/tmp/doctest.cover')
1654 else:
1655 test_main()