blob: c027acdcd652db97eb351d4c12ebf4cd7c3acc83 [file] [log] [blame]
Florent Xicluna2a903b22010-02-27 13:31:23 +00001# -*- coding: utf-8 -*-
Tim Peters8485b562004-08-04 18:46:34 +00002"""
3Test script for doctest.
4"""
5
Florent Xicluna6257a7b2010-03-31 22:01:03 +00006import sys
Barry Warsaw04f357c2002-07-23 19:04:11 +00007from test import test_support
Tim Peters8485b562004-08-04 18:46:34 +00008import doctest
9
Nick Coghlana2053472008-12-14 10:54:50 +000010# NOTE: There are some additional tests relating to interaction with
11# zipimport in the test_zipimport_support test module.
12
Tim Peters8485b562004-08-04 18:46:34 +000013######################################################################
14## Sample Objects (used by test cases)
15######################################################################
16
17def sample_func(v):
18 """
Tim Peters19397e52004-08-06 22:02:59 +000019 Blah blah
20
Tim Peters8485b562004-08-04 18:46:34 +000021 >>> print sample_func(22)
22 44
Tim Peters19397e52004-08-06 22:02:59 +000023
24 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000025 """
26 return v+v
27
28class SampleClass:
29 """
30 >>> print 1
31 1
Edward Loper4ae900f2004-09-21 03:20:34 +000032
33 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
34 >>>
35 ...
36
37 Multiline example:
38 >>> sc = SampleClass(3)
39 >>> for i in range(10):
40 ... sc = sc.double()
41 ... print sc.get(),
42 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000043 """
44 def __init__(self, val):
45 """
46 >>> print SampleClass(12).get()
47 12
48 """
49 self.val = val
50
51 def double(self):
52 """
53 >>> print SampleClass(12).double().get()
54 24
55 """
56 return SampleClass(self.val + self.val)
57
58 def get(self):
59 """
60 >>> print SampleClass(-5).get()
61 -5
62 """
63 return self.val
64
65 def a_staticmethod(v):
66 """
67 >>> print SampleClass.a_staticmethod(10)
68 11
69 """
70 return v+1
71 a_staticmethod = staticmethod(a_staticmethod)
72
73 def a_classmethod(cls, v):
74 """
75 >>> print SampleClass.a_classmethod(10)
76 12
77 >>> print SampleClass(0).a_classmethod(10)
78 12
79 """
80 return v+2
81 a_classmethod = classmethod(a_classmethod)
82
83 a_property = property(get, doc="""
84 >>> print SampleClass(22).a_property
85 22
86 """)
87
88 class NestedClass:
89 """
90 >>> x = SampleClass.NestedClass(5)
91 >>> y = x.square()
92 >>> print y.get()
93 25
94 """
95 def __init__(self, val=0):
96 """
97 >>> print SampleClass.NestedClass().get()
98 0
99 """
100 self.val = val
101 def square(self):
102 return SampleClass.NestedClass(self.val*self.val)
103 def get(self):
104 return self.val
105
106class SampleNewStyleClass(object):
107 r"""
108 >>> print '1\n2\n3'
109 1
110 2
111 3
112 """
113 def __init__(self, val):
114 """
115 >>> print SampleNewStyleClass(12).get()
116 12
117 """
118 self.val = val
119
120 def double(self):
121 """
122 >>> print SampleNewStyleClass(12).double().get()
123 24
124 """
125 return SampleNewStyleClass(self.val + self.val)
126
127 def get(self):
128 """
129 >>> print SampleNewStyleClass(-5).get()
130 -5
131 """
132 return self.val
133
134######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000135## Fake stdin (for testing interactive debugging)
136######################################################################
137
138class _FakeInput:
139 """
140 A fake input stream for pdb's interactive debugger. Whenever a
141 line is read, print it (to simulate the user typing it), and then
142 return it. The set of lines to return is specified in the
143 constructor; they should not have trailing newlines.
144 """
145 def __init__(self, lines):
146 self.lines = lines
147
148 def readline(self):
149 line = self.lines.pop(0)
150 print line
151 return line+'\n'
152
153######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000154## Test Cases
155######################################################################
156
157def test_Example(): r"""
158Unit tests for the `Example` class.
159
Edward Lopera6b68322004-08-26 00:05:43 +0000160Example is a simple container class that holds:
161 - `source`: A source string.
162 - `want`: An expected output string.
163 - `exc_msg`: An expected exception message string (or None if no
164 exception is expected).
165 - `lineno`: A line number (within the docstring).
166 - `indent`: The example's indentation in the input string.
167 - `options`: An option dictionary, mapping option flags to True or
168 False.
Tim Peters8485b562004-08-04 18:46:34 +0000169
Edward Lopera6b68322004-08-26 00:05:43 +0000170These attributes are set by the constructor. `source` and `want` are
171required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000172
Edward Lopera6b68322004-08-26 00:05:43 +0000173 >>> example = doctest.Example('print 1', '1\n')
174 >>> (example.source, example.want, example.exc_msg,
175 ... example.lineno, example.indent, example.options)
176 ('print 1\n', '1\n', None, 0, 0, {})
177
178The first three attributes (`source`, `want`, and `exc_msg`) may be
179specified positionally; the remaining arguments should be specified as
180keyword arguments:
181
182 >>> exc_msg = 'IndexError: pop from an empty list'
183 >>> example = doctest.Example('[].pop()', '', exc_msg,
184 ... lineno=5, indent=4,
185 ... options={doctest.ELLIPSIS: True})
186 >>> (example.source, example.want, example.exc_msg,
187 ... example.lineno, example.indent, example.options)
188 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
189
190The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000191
Tim Petersbb431472004-08-09 03:51:46 +0000192 Source spans a single line: no terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000193 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000194 >>> e.source, e.want
195 ('print 1\n', '1\n')
196
Edward Lopera6b68322004-08-26 00:05:43 +0000197 >>> e = doctest.Example('print 1\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000198 >>> e.source, e.want
199 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000200
Tim Petersbb431472004-08-09 03:51:46 +0000201 Source spans multiple lines: require terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000202 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000203 >>> e.source, e.want
204 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000205
Edward Lopera6b68322004-08-26 00:05:43 +0000206 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000207 >>> e.source, e.want
208 ('print 1;\nprint 2\n', '1\n2\n')
209
Edward Lopera6b68322004-08-26 00:05:43 +0000210 Empty source string (which should never appear in real examples)
211 >>> e = doctest.Example('', '')
212 >>> e.source, e.want
213 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000214
Edward Lopera6b68322004-08-26 00:05:43 +0000215The constructor normalizes the `want` string to end in a newline,
216unless it's the empty string:
217
218 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000219 >>> e.source, e.want
220 ('print 1\n', '1\n')
221
Edward Lopera6b68322004-08-26 00:05:43 +0000222 >>> e = doctest.Example('print 1', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000223 >>> e.source, e.want
224 ('print 1\n', '1\n')
225
Edward Lopera6b68322004-08-26 00:05:43 +0000226 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000227 >>> e.source, e.want
228 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000229
230The constructor normalizes the `exc_msg` string to end in a newline,
231unless it's `None`:
232
233 Message spans one line
234 >>> exc_msg = 'IndexError: pop from an empty list'
235 >>> e = doctest.Example('[].pop()', '', exc_msg)
236 >>> e.exc_msg
237 'IndexError: pop from an empty list\n'
238
239 >>> exc_msg = 'IndexError: pop from an empty list\n'
240 >>> e = doctest.Example('[].pop()', '', exc_msg)
241 >>> e.exc_msg
242 'IndexError: pop from an empty list\n'
243
244 Message spans multiple lines
245 >>> exc_msg = 'ValueError: 1\n 2'
246 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
247 >>> e.exc_msg
248 'ValueError: 1\n 2\n'
249
250 >>> exc_msg = 'ValueError: 1\n 2\n'
251 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
252 >>> e.exc_msg
253 'ValueError: 1\n 2\n'
254
255 Empty (but non-None) exception message (which should never appear
256 in real examples)
257 >>> exc_msg = ''
258 >>> e = doctest.Example('raise X()', '', exc_msg)
259 >>> e.exc_msg
260 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000261"""
262
263def test_DocTest(): r"""
264Unit tests for the `DocTest` class.
265
266DocTest is a collection of examples, extracted from a docstring, along
267with information about where the docstring comes from (a name,
268filename, and line number). The docstring is parsed by the `DocTest`
269constructor:
270
271 >>> docstring = '''
272 ... >>> print 12
273 ... 12
274 ...
275 ... Non-example text.
276 ...
277 ... >>> print 'another\example'
278 ... another
279 ... example
280 ... '''
281 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000282 >>> parser = doctest.DocTestParser()
283 >>> test = parser.get_doctest(docstring, globs, 'some_test',
284 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000285 >>> print test
286 <DocTest some_test from some_file:20 (2 examples)>
287 >>> len(test.examples)
288 2
289 >>> e1, e2 = test.examples
290 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000291 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000292 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000293 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000294
295Source information (name, filename, and line number) is available as
296attributes on the doctest object:
297
298 >>> (test.name, test.filename, test.lineno)
299 ('some_test', 'some_file', 20)
300
301The line number of an example within its containing file is found by
302adding the line number of the example and the line number of its
303containing test:
304
305 >>> test.lineno + e1.lineno
306 21
307 >>> test.lineno + e2.lineno
308 26
309
310If the docstring contains inconsistant leading whitespace in the
311expected output of an example, then `DocTest` will raise a ValueError:
312
313 >>> docstring = r'''
314 ... >>> print 'bad\nindentation'
315 ... bad
316 ... indentation
317 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000318 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000319 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000320 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000321
322If the docstring contains inconsistent leading whitespace on
323continuation lines, then `DocTest` will raise a ValueError:
324
325 >>> docstring = r'''
326 ... >>> print ('bad indentation',
327 ... ... 2)
328 ... ('bad', 'indentation')
329 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000330 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000331 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000332 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
Tim Peters8485b562004-08-04 18:46:34 +0000333
334If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
335will raise a ValueError:
336
337 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000338 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000339 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000340 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
341
342If there's no blank space after a PS2 prompt ('...'), then `DocTest`
343will raise a ValueError:
344
345 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000346 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000347 Traceback (most recent call last):
348 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
349
Tim Peters8485b562004-08-04 18:46:34 +0000350"""
351
Tim Peters8485b562004-08-04 18:46:34 +0000352def test_DocTestFinder(): r"""
353Unit tests for the `DocTestFinder` class.
354
355DocTestFinder is used to extract DocTests from an object's docstring
356and the docstrings of its contained objects. It can be used with
357modules, functions, classes, methods, staticmethods, classmethods, and
358properties.
359
360Finding Tests in Functions
361~~~~~~~~~~~~~~~~~~~~~~~~~~
362For a function whose docstring contains examples, DocTestFinder.find()
363will return a single test (for that function's docstring):
364
Tim Peters8485b562004-08-04 18:46:34 +0000365 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000366
367We'll simulate a __file__ attr that ends in pyc:
368
369 >>> import test.test_doctest
370 >>> old = test.test_doctest.__file__
371 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
372
Tim Peters8485b562004-08-04 18:46:34 +0000373 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000374
Edward Loper74bca7a2004-08-12 02:27:44 +0000375 >>> print tests # doctest: +ELLIPSIS
Florent Xicluna2a903b22010-02-27 13:31:23 +0000376 [<DocTest sample_func from ...:17 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000377
Tim Peters4de7c5c2004-08-23 22:38:05 +0000378The exact name depends on how test_doctest was invoked, so allow for
379leading path components.
380
381 >>> tests[0].filename # doctest: +ELLIPSIS
382 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000383
384 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000385
Jim Fulton07a349c2004-08-22 14:10:00 +0000386
Tim Peters8485b562004-08-04 18:46:34 +0000387 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000388 >>> (e.source, e.want, e.lineno)
389 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000390
Edward Loper32ddbf72004-09-13 05:47:24 +0000391By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000392
393 >>> def no_docstring(v):
394 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000395 >>> finder.find(no_docstring)
396 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000397
398However, the optional argument `exclude_empty` to the DocTestFinder
399constructor can be used to exclude tests for objects with empty
400docstrings:
401
402 >>> def no_docstring(v):
403 ... pass
404 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
405 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000406 []
407
408If the function has a docstring with no examples, then a test with no
409examples is returned. (This lets `DocTestRunner` collect statistics
410about which functions have no tests -- but is that useful? And should
411an empty test also be created when there's no docstring?)
412
413 >>> def no_examples(v):
414 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000415 >>> finder.find(no_examples) # doctest: +ELLIPSIS
416 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000417
418Finding Tests in Classes
419~~~~~~~~~~~~~~~~~~~~~~~~
420For a class, DocTestFinder will create a test for the class's
421docstring, and will recursively explore its contents, including
422methods, classmethods, staticmethods, properties, and nested classes.
423
424 >>> finder = doctest.DocTestFinder()
425 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000426 >>> for t in tests:
427 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000428 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000429 3 SampleClass.NestedClass
430 1 SampleClass.NestedClass.__init__
431 1 SampleClass.__init__
432 2 SampleClass.a_classmethod
433 1 SampleClass.a_property
434 1 SampleClass.a_staticmethod
435 1 SampleClass.double
436 1 SampleClass.get
437
438New-style classes are also supported:
439
440 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000441 >>> for t in tests:
442 ... print '%2s %s' % (len(t.examples), t.name)
443 1 SampleNewStyleClass
444 1 SampleNewStyleClass.__init__
445 1 SampleNewStyleClass.double
446 1 SampleNewStyleClass.get
447
448Finding Tests in Modules
449~~~~~~~~~~~~~~~~~~~~~~~~
450For a module, DocTestFinder will create a test for the class's
451docstring, and will recursively explore its contents, including
452functions, classes, and the `__test__` dictionary, if it exists:
453
454 >>> # A module
Christian Heimesc756d002007-11-27 21:34:01 +0000455 >>> import types
456 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000457 >>> def triple(val):
458 ... '''
Edward Loper4ae900f2004-09-21 03:20:34 +0000459 ... >>> print triple(11)
Tim Peters8485b562004-08-04 18:46:34 +0000460 ... 33
461 ... '''
462 ... return val*3
463 >>> m.__dict__.update({
464 ... 'sample_func': sample_func,
465 ... 'SampleClass': SampleClass,
466 ... '__doc__': '''
467 ... Module docstring.
468 ... >>> print 'module'
469 ... module
470 ... ''',
471 ... '__test__': {
472 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
473 ... 'c': triple}})
474
475 >>> finder = doctest.DocTestFinder()
476 >>> # Use module=test.test_doctest, to prevent doctest from
477 >>> # ignoring the objects since they weren't defined in m.
478 >>> import test.test_doctest
479 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000480 >>> for t in tests:
481 ... print '%2s %s' % (len(t.examples), t.name)
482 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000483 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000484 3 some_module.SampleClass.NestedClass
485 1 some_module.SampleClass.NestedClass.__init__
486 1 some_module.SampleClass.__init__
487 2 some_module.SampleClass.a_classmethod
488 1 some_module.SampleClass.a_property
489 1 some_module.SampleClass.a_staticmethod
490 1 some_module.SampleClass.double
491 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000492 1 some_module.__test__.c
493 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000494 1 some_module.sample_func
495
496Duplicate Removal
497~~~~~~~~~~~~~~~~~
498If a single object is listed twice (under different names), then tests
499will only be generated for it once:
500
Tim Petersf3f57472004-08-08 06:11:48 +0000501 >>> from test import doctest_aliases
Amaury Forgeot d'Arcf81ff982009-06-14 21:20:40 +0000502 >>> assert doctest_aliases.TwoNames.f
503 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000504 >>> tests = excl_empty_finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000505 >>> print len(tests)
506 2
507 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000508 test.doctest_aliases.TwoNames
509
510 TwoNames.f and TwoNames.g are bound to the same object.
511 We can't guess which will be found in doctest's traversal of
512 TwoNames.__dict__ first, so we have to allow for either.
513
514 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000515 True
516
Tim Petersbf0400a2006-06-05 01:43:03 +0000517Empty Tests
518~~~~~~~~~~~
519By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000520
Tim Petersbf0400a2006-06-05 01:43:03 +0000521 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000522 >>> for t in tests:
523 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000524 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000525 3 SampleClass.NestedClass
526 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000527 1 SampleClass.__init__
Tim Petersbf0400a2006-06-05 01:43:03 +0000528 2 SampleClass.a_classmethod
529 1 SampleClass.a_property
530 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000531 1 SampleClass.double
532 1 SampleClass.get
533
534By default, that excluded objects with no doctests. exclude_empty=False
535tells it to include (empty) tests for objects with no doctests. This feature
536is really to support backward compatibility in what doctest.master.summarize()
537displays.
538
Tim Petersbf0400a2006-06-05 01:43:03 +0000539 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000540 >>> for t in tests:
541 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000542 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000543 3 SampleClass.NestedClass
544 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000545 0 SampleClass.NestedClass.get
546 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000547 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000548 2 SampleClass.a_classmethod
549 1 SampleClass.a_property
550 1 SampleClass.a_staticmethod
551 1 SampleClass.double
552 1 SampleClass.get
553
Tim Peters8485b562004-08-04 18:46:34 +0000554Turning off Recursion
555~~~~~~~~~~~~~~~~~~~~~
556DocTestFinder can be told not to look for tests in contained objects
557using the `recurse` flag:
558
559 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000560 >>> for t in tests:
561 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000562 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000563
564Line numbers
565~~~~~~~~~~~~
566DocTestFinder finds the line number of each example:
567
568 >>> def f(x):
569 ... '''
570 ... >>> x = 12
571 ...
572 ... some text
573 ...
574 ... >>> # examples are not created for comments & bare prompts.
575 ... >>>
576 ... ...
577 ...
578 ... >>> for x in range(10):
579 ... ... print x,
580 ... 0 1 2 3 4 5 6 7 8 9
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000581 ... >>> x//2
Edward Loperb51b2342004-08-17 16:37:12 +0000582 ... 6
583 ... '''
584 >>> test = doctest.DocTestFinder().find(f)[0]
585 >>> [e.lineno for e in test.examples]
586 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000587"""
588
Edward Loper00f8da72004-08-26 18:05:07 +0000589def test_DocTestParser(): r"""
590Unit tests for the `DocTestParser` class.
591
592DocTestParser is used to parse docstrings containing doctest examples.
593
594The `parse` method divides a docstring into examples and intervening
595text:
596
597 >>> s = '''
598 ... >>> x, y = 2, 3 # no output expected
599 ... >>> if 1:
600 ... ... print x
601 ... ... print y
602 ... 2
603 ... 3
604 ...
605 ... Some text.
606 ... >>> x+y
607 ... 5
608 ... '''
609 >>> parser = doctest.DocTestParser()
610 >>> for piece in parser.parse(s):
611 ... if isinstance(piece, doctest.Example):
612 ... print 'Example:', (piece.source, piece.want, piece.lineno)
613 ... else:
614 ... print ' Text:', `piece`
615 Text: '\n'
616 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
617 Text: ''
618 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
619 Text: '\nSome text.\n'
620 Example: ('x+y\n', '5\n', 9)
621 Text: ''
622
623The `get_examples` method returns just the examples:
624
625 >>> for piece in parser.get_examples(s):
626 ... print (piece.source, piece.want, piece.lineno)
627 ('x, y = 2, 3 # no output expected\n', '', 1)
628 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
629 ('x+y\n', '5\n', 9)
630
631The `get_doctest` method creates a Test from the examples, along with the
632given arguments:
633
634 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
635 >>> (test.name, test.filename, test.lineno)
636 ('name', 'filename', 5)
637 >>> for piece in test.examples:
638 ... print (piece.source, piece.want, piece.lineno)
639 ('x, y = 2, 3 # no output expected\n', '', 1)
640 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
641 ('x+y\n', '5\n', 9)
642"""
643
Tim Peters8485b562004-08-04 18:46:34 +0000644class test_DocTestRunner:
645 def basics(): r"""
646Unit tests for the `DocTestRunner` class.
647
648DocTestRunner is used to run DocTest test cases, and to accumulate
649statistics. Here's a simple DocTest case we can use:
650
651 >>> def f(x):
652 ... '''
653 ... >>> x = 12
654 ... >>> print x
655 ... 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000656 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000657 ... 6
658 ... '''
659 >>> test = doctest.DocTestFinder().find(f)[0]
660
661The main DocTestRunner interface is the `run` method, which runs a
662given DocTest case in a given namespace (globs). It returns a tuple
663`(f,t)`, where `f` is the number of failed tests and `t` is the number
664of tried tests.
665
666 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000667 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000668
669If any example produces incorrect output, then the test runner reports
670the failure and proceeds to the next example:
671
672 >>> def f(x):
673 ... '''
674 ... >>> x = 12
675 ... >>> print x
676 ... 14
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000677 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000678 ... 6
679 ... '''
680 >>> test = doctest.DocTestFinder().find(f)[0]
681 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000682 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000683 Trying:
684 x = 12
685 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000686 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000687 Trying:
688 print x
689 Expecting:
690 14
Tim Peters8485b562004-08-04 18:46:34 +0000691 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000692 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000693 Failed example:
694 print x
695 Expected:
696 14
697 Got:
698 12
Edward Loperaacf0832004-08-26 01:19:50 +0000699 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000700 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000701 Expecting:
702 6
Tim Peters8485b562004-08-04 18:46:34 +0000703 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000704 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000705"""
706 def verbose_flag(): r"""
707The `verbose` flag makes the test runner generate more detailed
708output:
709
710 >>> def f(x):
711 ... '''
712 ... >>> x = 12
713 ... >>> print x
714 ... 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000715 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000716 ... 6
717 ... '''
718 >>> test = doctest.DocTestFinder().find(f)[0]
719
720 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000721 Trying:
722 x = 12
723 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000724 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000725 Trying:
726 print x
727 Expecting:
728 12
Tim Peters8485b562004-08-04 18:46:34 +0000729 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000730 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000731 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000732 Expecting:
733 6
Tim Peters8485b562004-08-04 18:46:34 +0000734 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000735 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000736
737If the `verbose` flag is unspecified, then the output will be verbose
738iff `-v` appears in sys.argv:
739
740 >>> # Save the real sys.argv list.
741 >>> old_argv = sys.argv
742
743 >>> # If -v does not appear in sys.argv, then output isn't verbose.
744 >>> sys.argv = ['test']
745 >>> doctest.DocTestRunner().run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000746 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000747
748 >>> # If -v does appear in sys.argv, then output is verbose.
749 >>> sys.argv = ['test', '-v']
750 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000751 Trying:
752 x = 12
753 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000754 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000755 Trying:
756 print x
757 Expecting:
758 12
Tim Peters8485b562004-08-04 18:46:34 +0000759 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000760 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000761 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000762 Expecting:
763 6
Tim Peters8485b562004-08-04 18:46:34 +0000764 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000765 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000766
767 >>> # Restore sys.argv
768 >>> sys.argv = old_argv
769
770In the remaining examples, the test runner's verbosity will be
771explicitly set, to ensure that the test behavior is consistent.
772 """
773 def exceptions(): r"""
774Tests of `DocTestRunner`'s exception handling.
775
776An expected exception is specified with a traceback message. The
777lines between the first line and the type/value may be omitted or
778replaced with any other string:
779
780 >>> def f(x):
781 ... '''
782 ... >>> x = 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000783 ... >>> print x//0
Tim Peters8485b562004-08-04 18:46:34 +0000784 ... Traceback (most recent call last):
785 ... ZeroDivisionError: integer division or modulo by zero
786 ... '''
787 >>> test = doctest.DocTestFinder().find(f)[0]
788 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000789 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000790
Edward Loper19b19582004-08-25 23:07:03 +0000791An example may not generate output before it raises an exception; if
792it does, then the traceback message will not be recognized as
793signaling an expected exception, so the example will be reported as an
794unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000795
796 >>> def f(x):
797 ... '''
798 ... >>> x = 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000799 ... >>> print 'pre-exception output', x//0
Tim Peters8485b562004-08-04 18:46:34 +0000800 ... pre-exception output
801 ... Traceback (most recent call last):
802 ... ZeroDivisionError: integer division or modulo by zero
803 ... '''
804 >>> test = doctest.DocTestFinder().find(f)[0]
805 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000806 ... # doctest: +ELLIPSIS
807 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000808 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000809 Failed example:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000810 print 'pre-exception output', x//0
Edward Loper19b19582004-08-25 23:07:03 +0000811 Exception raised:
812 ...
813 ZeroDivisionError: integer division or modulo by zero
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000814 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000815
816Exception messages may contain newlines:
817
818 >>> def f(x):
819 ... r'''
820 ... >>> raise ValueError, 'multi\nline\nmessage'
821 ... Traceback (most recent call last):
822 ... ValueError: multi
823 ... line
824 ... message
825 ... '''
826 >>> test = doctest.DocTestFinder().find(f)[0]
827 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000828 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000829
830If an exception is expected, but an exception with the wrong type or
831message is raised, then it is reported as a failure:
832
833 >>> def f(x):
834 ... r'''
835 ... >>> raise ValueError, 'message'
836 ... Traceback (most recent call last):
837 ... ValueError: wrong message
838 ... '''
839 >>> test = doctest.DocTestFinder().find(f)[0]
840 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000841 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000842 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000843 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000844 Failed example:
845 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000846 Expected:
847 Traceback (most recent call last):
848 ValueError: wrong message
849 Got:
850 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000851 ...
Tim Peters8485b562004-08-04 18:46:34 +0000852 ValueError: message
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000853 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000854
Tim Peters1fbf9c52004-09-04 17:21:02 +0000855However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
856detail:
857
858 >>> def f(x):
859 ... r'''
860 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
861 ... Traceback (most recent call last):
862 ... ValueError: wrong message
863 ... '''
864 >>> test = doctest.DocTestFinder().find(f)[0]
865 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000866 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000867
Nick Coghlandfb45df2010-04-28 14:29:06 +0000868IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
869between Python versions. For example, in Python 3.x, the module path of
870the exception is in the output, but this will fail under Python 2:
871
872 >>> def f(x):
873 ... r'''
874 ... >>> from httplib import HTTPException
875 ... >>> raise HTTPException('message')
876 ... Traceback (most recent call last):
877 ... httplib.HTTPException: message
878 ... '''
879 >>> test = doctest.DocTestFinder().find(f)[0]
880 >>> doctest.DocTestRunner(verbose=False).run(test)
881 ... # doctest: +ELLIPSIS
882 **********************************************************************
883 File ..., line 4, in f
884 Failed example:
885 raise HTTPException('message')
886 Expected:
887 Traceback (most recent call last):
888 httplib.HTTPException: message
889 Got:
890 Traceback (most recent call last):
891 ...
892 HTTPException: message
893 TestResults(failed=1, attempted=2)
894
895But in Python 2 the module path is not included, an therefore a test must look
896like the following test to succeed in Python 2. But that test will fail under
897Python 3.
898
899 >>> def f(x):
900 ... r'''
901 ... >>> from httplib import HTTPException
902 ... >>> raise HTTPException('message')
903 ... Traceback (most recent call last):
904 ... HTTPException: message
905 ... '''
906 >>> test = doctest.DocTestFinder().find(f)[0]
907 >>> doctest.DocTestRunner(verbose=False).run(test)
908 TestResults(failed=0, attempted=2)
909
910However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
911(if any) will be ignored:
912
913 >>> def f(x):
914 ... r'''
915 ... >>> from httplib import HTTPException
916 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
917 ... Traceback (most recent call last):
918 ... HTTPException: message
919 ... '''
920 >>> test = doctest.DocTestFinder().find(f)[0]
921 >>> doctest.DocTestRunner(verbose=False).run(test)
922 TestResults(failed=0, attempted=2)
923
924The module path will be completely ignored, so two different module paths will
925still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
926be used when exceptions have changed module.
927
928 >>> def f(x):
929 ... r'''
930 ... >>> from httplib import HTTPException
931 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
932 ... Traceback (most recent call last):
933 ... foo.bar.HTTPException: message
934 ... '''
935 >>> test = doctest.DocTestFinder().find(f)[0]
936 >>> doctest.DocTestRunner(verbose=False).run(test)
937 TestResults(failed=0, attempted=2)
938
Tim Peters1fbf9c52004-09-04 17:21:02 +0000939But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
940
941 >>> def f(x):
942 ... r'''
943 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
944 ... Traceback (most recent call last):
945 ... TypeError: wrong type
946 ... '''
947 >>> test = doctest.DocTestFinder().find(f)[0]
948 >>> doctest.DocTestRunner(verbose=False).run(test)
949 ... # doctest: +ELLIPSIS
950 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000951 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000952 Failed example:
953 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
954 Expected:
955 Traceback (most recent call last):
956 TypeError: wrong type
957 Got:
958 Traceback (most recent call last):
959 ...
960 ValueError: message
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000961 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000962
Tim Peters8485b562004-08-04 18:46:34 +0000963If an exception is raised but not expected, then it is reported as an
964unexpected exception:
965
Tim Peters8485b562004-08-04 18:46:34 +0000966 >>> def f(x):
967 ... r'''
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000968 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000969 ... 0
970 ... '''
971 >>> test = doctest.DocTestFinder().find(f)[0]
972 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000973 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000974 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000975 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000976 Failed example:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000977 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000978 Exception raised:
979 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000980 ...
Tim Peters8485b562004-08-04 18:46:34 +0000981 ZeroDivisionError: integer division or modulo by zero
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000982 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000983"""
Georg Brandl50775992010-08-01 19:33:15 +0000984 def displayhook(): r"""
985Test that changing sys.displayhook doesn't matter for doctest.
986
987 >>> import sys
988 >>> orig_displayhook = sys.displayhook
989 >>> def my_displayhook(x):
990 ... print('hi!')
991 >>> sys.displayhook = my_displayhook
992 >>> def f():
993 ... '''
994 ... >>> 3
995 ... 3
996 ... '''
997 >>> test = doctest.DocTestFinder().find(f)[0]
998 >>> r = doctest.DocTestRunner(verbose=False).run(test)
999 >>> post_displayhook = sys.displayhook
1000
1001 We need to restore sys.displayhook now, so that we'll be able to test
1002 results.
1003
1004 >>> sys.displayhook = orig_displayhook
1005
1006 Ok, now we can check that everything is ok.
1007
1008 >>> r
1009 TestResults(failed=0, attempted=1)
1010 >>> post_displayhook is my_displayhook
1011 True
1012"""
Tim Peters8485b562004-08-04 18:46:34 +00001013 def optionflags(): r"""
1014Tests of `DocTestRunner`'s option flag handling.
1015
1016Several option flags can be used to customize the behavior of the test
1017runner. These are defined as module constants in doctest, and passed
Georg Brandlf725b952008-01-05 19:44:22 +00001018to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001019together).
1020
1021The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1022and 1/0:
1023
1024 >>> def f(x):
1025 ... '>>> True\n1\n'
1026
1027 >>> # Without the flag:
1028 >>> test = doctest.DocTestFinder().find(f)[0]
1029 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001030 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001031
1032 >>> # With the flag:
1033 >>> test = doctest.DocTestFinder().find(f)[0]
1034 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1035 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001036 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001037 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001038 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001039 Failed example:
1040 True
1041 Expected:
1042 1
1043 Got:
1044 True
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001045 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001046
1047The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1048and the '<BLANKLINE>' marker:
1049
1050 >>> def f(x):
1051 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
1052
1053 >>> # Without the flag:
1054 >>> test = doctest.DocTestFinder().find(f)[0]
1055 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001056 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001057
1058 >>> # With the flag:
1059 >>> test = doctest.DocTestFinder().find(f)[0]
1060 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1061 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001062 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001063 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001064 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001065 Failed example:
1066 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +00001067 Expected:
1068 a
1069 <BLANKLINE>
1070 b
1071 Got:
1072 a
1073 <BLANKLINE>
1074 b
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001075 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001076
1077The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1078treated as equal:
1079
1080 >>> def f(x):
1081 ... '>>> print 1, 2, 3\n 1 2\n 3'
1082
1083 >>> # Without the flag:
1084 >>> test = doctest.DocTestFinder().find(f)[0]
1085 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001086 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001087 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001088 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001089 Failed example:
1090 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +00001091 Expected:
1092 1 2
1093 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001094 Got:
1095 1 2 3
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001096 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001097
1098 >>> # With the flag:
1099 >>> test = doctest.DocTestFinder().find(f)[0]
1100 >>> flags = doctest.NORMALIZE_WHITESPACE
1101 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001102 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001103
Tim Peters026f8dc2004-08-19 16:38:58 +00001104 An example from the docs:
1105 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
1106 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1107 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1108
Tim Peters8485b562004-08-04 18:46:34 +00001109The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1110output to match any substring in the actual output:
1111
1112 >>> def f(x):
1113 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1114
1115 >>> # Without the flag:
1116 >>> test = doctest.DocTestFinder().find(f)[0]
1117 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001118 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001119 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001120 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001121 Failed example:
1122 print range(15)
1123 Expected:
1124 [0, 1, 2, ..., 14]
1125 Got:
1126 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001127 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001128
1129 >>> # With the flag:
1130 >>> test = doctest.DocTestFinder().find(f)[0]
1131 >>> flags = doctest.ELLIPSIS
1132 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001133 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001134
Tim Peterse594bee2004-08-22 01:47:51 +00001135 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001136
1137 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001138 ... print i**2, #doctest: +ELLIPSIS
1139 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001140
Tim Peters026f8dc2004-08-19 16:38:58 +00001141 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001142
1143 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001144 ... print i,
1145 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001146
Tim Peters026f8dc2004-08-19 16:38:58 +00001147 Examples from the docs:
1148
1149 >>> print range(20) # doctest:+ELLIPSIS
1150 [0, 1, ..., 18, 19]
1151
1152 >>> print range(20) # doctest: +ELLIPSIS
1153 ... # doctest: +NORMALIZE_WHITESPACE
1154 [0, 1, ..., 18, 19]
1155
Tim Peters711bf302006-04-25 03:31:36 +00001156The SKIP flag causes an example to be skipped entirely. I.e., the
1157example is not run. It can be useful in contexts where doctest
1158examples serve as both documentation and test cases, and an example
1159should be included for documentation purposes, but should not be
1160checked (e.g., because its output is random, or depends on resources
1161which would be unavailable.) The SKIP flag can also be used for
1162'commenting out' broken examples.
1163
1164 >>> import unavailable_resource # doctest: +SKIP
1165 >>> unavailable_resource.do_something() # doctest: +SKIP
1166 >>> unavailable_resource.blow_up() # doctest: +SKIP
1167 Traceback (most recent call last):
1168 ...
1169 UncheckedBlowUpError: Nobody checks me.
1170
1171 >>> import random
1172 >>> print random.random() # doctest: +SKIP
1173 0.721216923889
1174
Edward Loper71f55af2004-08-26 01:41:51 +00001175The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001176and actual outputs to be displayed using a unified diff:
1177
1178 >>> def f(x):
1179 ... r'''
1180 ... >>> print '\n'.join('abcdefg')
1181 ... a
1182 ... B
1183 ... c
1184 ... d
1185 ... f
1186 ... g
1187 ... h
1188 ... '''
1189
1190 >>> # Without the flag:
1191 >>> test = doctest.DocTestFinder().find(f)[0]
1192 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001193 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001194 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001195 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001196 Failed example:
1197 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001198 Expected:
1199 a
1200 B
1201 c
1202 d
1203 f
1204 g
1205 h
1206 Got:
1207 a
1208 b
1209 c
1210 d
1211 e
1212 f
1213 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001214 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001215
1216 >>> # With the flag:
1217 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001218 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001219 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001220 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001221 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001222 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001223 Failed example:
1224 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001225 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001226 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001227 a
1228 -B
1229 +b
1230 c
1231 d
1232 +e
1233 f
1234 g
1235 -h
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001236 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001237
Edward Loper71f55af2004-08-26 01:41:51 +00001238The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001239and actual outputs to be displayed using a context diff:
1240
Edward Loper71f55af2004-08-26 01:41:51 +00001241 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001242 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001243 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001244 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001245 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001246 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001247 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001248 Failed example:
1249 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001250 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001251 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001252 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001253 a
1254 ! B
1255 c
1256 d
1257 f
1258 g
1259 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001260 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001261 a
1262 ! b
1263 c
1264 d
1265 + e
1266 f
1267 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001268 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001269
1270
Edward Loper71f55af2004-08-26 01:41:51 +00001271The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001272used by the popular ndiff.py utility. This does intraline difference
1273marking, as well as interline differences.
1274
1275 >>> def f(x):
1276 ... r'''
1277 ... >>> print "a b c d e f g h i j k l m"
1278 ... a b c d e f g h i j k 1 m
1279 ... '''
1280 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001281 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001282 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001283 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001284 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001285 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001286 Failed example:
1287 print "a b c d e f g h i j k l m"
1288 Differences (ndiff with -expected +actual):
1289 - a b c d e f g h i j k 1 m
1290 ? ^
1291 + a b c d e f g h i j k l m
1292 ? + ++ ^
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001293 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001294
1295The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1296failing example:
1297
1298 >>> def f(x):
1299 ... r'''
1300 ... >>> print 1 # first success
1301 ... 1
1302 ... >>> print 2 # first failure
1303 ... 200
1304 ... >>> print 3 # second failure
1305 ... 300
1306 ... >>> print 4 # second success
1307 ... 4
1308 ... >>> print 5 # third failure
1309 ... 500
1310 ... '''
1311 >>> test = doctest.DocTestFinder().find(f)[0]
1312 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1313 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001314 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001315 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001316 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001317 Failed example:
1318 print 2 # first failure
1319 Expected:
1320 200
1321 Got:
1322 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001323 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001324
1325However, output from `report_start` is not supressed:
1326
1327 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001328 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001329 Trying:
1330 print 1 # first success
1331 Expecting:
1332 1
1333 ok
1334 Trying:
1335 print 2 # first failure
1336 Expecting:
1337 200
1338 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001339 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001340 Failed example:
1341 print 2 # first failure
1342 Expected:
1343 200
1344 Got:
1345 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001346 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001347
1348For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1349count as failures:
1350
1351 >>> def f(x):
1352 ... r'''
1353 ... >>> print 1 # first success
1354 ... 1
1355 ... >>> raise ValueError(2) # first failure
1356 ... 200
1357 ... >>> print 3 # second failure
1358 ... 300
1359 ... >>> print 4 # second success
1360 ... 4
1361 ... >>> print 5 # third failure
1362 ... 500
1363 ... '''
1364 >>> test = doctest.DocTestFinder().find(f)[0]
1365 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1366 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1367 ... # doctest: +ELLIPSIS
1368 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001369 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001370 Failed example:
1371 raise ValueError(2) # first failure
1372 Exception raised:
1373 ...
1374 ValueError: 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001375 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001376
Tim Petersad2ef332006-05-10 02:43:01 +00001377New option flags can also be registered, via register_optionflag(). Here
1378we reach into doctest's internals a bit.
1379
1380 >>> unlikely = "UNLIKELY_OPTION_NAME"
1381 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1382 False
1383 >>> new_flag_value = doctest.register_optionflag(unlikely)
1384 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1385 True
1386
1387Before 2.4.4/2.5, registering a name more than once erroneously created
1388more than one flag value. Here we verify that's fixed:
1389
1390 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1391 >>> redundant_flag_value == new_flag_value
1392 True
1393
1394Clean up.
1395 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1396
Tim Petersc6cbab02004-08-22 19:43:28 +00001397 """
1398
Tim Peters8485b562004-08-04 18:46:34 +00001399 def option_directives(): r"""
1400Tests of `DocTestRunner`'s option directive mechanism.
1401
Edward Loper74bca7a2004-08-12 02:27:44 +00001402Option directives can be used to turn option flags on or off for a
1403single example. To turn an option on for an example, follow that
1404example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001405
1406 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001407 ... >>> print range(10) # should fail: no ellipsis
1408 ... [0, 1, ..., 9]
1409 ...
1410 ... >>> print range(10) # doctest: +ELLIPSIS
1411 ... [0, 1, ..., 9]
1412 ... '''
1413 >>> test = doctest.DocTestFinder().find(f)[0]
1414 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001415 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001416 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001417 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001418 Failed example:
1419 print range(10) # should fail: no ellipsis
1420 Expected:
1421 [0, 1, ..., 9]
1422 Got:
1423 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001424 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001425
1426To turn an option off for an example, follow that example with a
1427comment of the form ``# doctest: -OPTION``:
1428
1429 >>> def f(x): r'''
1430 ... >>> print range(10)
1431 ... [0, 1, ..., 9]
1432 ...
1433 ... >>> # should fail: no ellipsis
1434 ... >>> print range(10) # doctest: -ELLIPSIS
1435 ... [0, 1, ..., 9]
1436 ... '''
1437 >>> test = doctest.DocTestFinder().find(f)[0]
1438 >>> doctest.DocTestRunner(verbose=False,
1439 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001440 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001441 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001442 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001443 Failed example:
1444 print range(10) # doctest: -ELLIPSIS
1445 Expected:
1446 [0, 1, ..., 9]
1447 Got:
1448 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001449 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001450
1451Option directives affect only the example that they appear with; they
1452do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001453
Edward Loper74bca7a2004-08-12 02:27:44 +00001454 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001455 ... >>> print range(10) # Should fail: no ellipsis
1456 ... [0, 1, ..., 9]
1457 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001458 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001459 ... [0, 1, ..., 9]
1460 ...
Tim Peters8485b562004-08-04 18:46:34 +00001461 ... >>> print range(10) # Should fail: no ellipsis
1462 ... [0, 1, ..., 9]
1463 ... '''
1464 >>> test = doctest.DocTestFinder().find(f)[0]
1465 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001466 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001467 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001468 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001469 Failed example:
1470 print range(10) # Should fail: no ellipsis
1471 Expected:
1472 [0, 1, ..., 9]
1473 Got:
1474 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001475 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001476 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001477 Failed example:
1478 print range(10) # Should fail: no ellipsis
1479 Expected:
1480 [0, 1, ..., 9]
1481 Got:
1482 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001483 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001484
Edward Loper74bca7a2004-08-12 02:27:44 +00001485Multiple options may be modified by a single option directive. They
1486may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001487
1488 >>> def f(x): r'''
1489 ... >>> print range(10) # Should fail
1490 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001491 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001492 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001493 ... [0, 1, ..., 9]
1494 ... '''
1495 >>> test = doctest.DocTestFinder().find(f)[0]
1496 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001497 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001498 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001499 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001500 Failed example:
1501 print range(10) # Should fail
1502 Expected:
1503 [0, 1, ..., 9]
1504 Got:
1505 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001506 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001507
1508 >>> def f(x): r'''
1509 ... >>> print range(10) # Should fail
1510 ... [0, 1, ..., 9]
1511 ... >>> print range(10) # Should succeed
1512 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1513 ... [0, 1, ..., 9]
1514 ... '''
1515 >>> test = doctest.DocTestFinder().find(f)[0]
1516 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001517 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001518 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001519 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001520 Failed example:
1521 print range(10) # Should fail
1522 Expected:
1523 [0, 1, ..., 9]
1524 Got:
1525 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001526 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001527
1528 >>> def f(x): r'''
1529 ... >>> print range(10) # Should fail
1530 ... [0, 1, ..., 9]
1531 ... >>> print range(10) # Should succeed
1532 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1533 ... [0, 1, ..., 9]
1534 ... '''
1535 >>> test = doctest.DocTestFinder().find(f)[0]
1536 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001537 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001538 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001539 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001540 Failed example:
1541 print range(10) # Should fail
1542 Expected:
1543 [0, 1, ..., 9]
1544 Got:
1545 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001546 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001547
1548The option directive may be put on the line following the source, as
1549long as a continuation prompt is used:
1550
1551 >>> def f(x): r'''
1552 ... >>> print range(10)
1553 ... ... # doctest: +ELLIPSIS
1554 ... [0, 1, ..., 9]
1555 ... '''
1556 >>> test = doctest.DocTestFinder().find(f)[0]
1557 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001558 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001559
Edward Loper74bca7a2004-08-12 02:27:44 +00001560For examples with multi-line source, the option directive may appear
1561at the end of any line:
1562
1563 >>> def f(x): r'''
1564 ... >>> for x in range(10): # doctest: +ELLIPSIS
1565 ... ... print x,
1566 ... 0 1 2 ... 9
1567 ...
1568 ... >>> for x in range(10):
1569 ... ... print x, # doctest: +ELLIPSIS
1570 ... 0 1 2 ... 9
1571 ... '''
1572 >>> test = doctest.DocTestFinder().find(f)[0]
1573 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001574 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001575
1576If more than one line of an example with multi-line source has an
1577option directive, then they are combined:
1578
1579 >>> def f(x): r'''
1580 ... Should fail (option directive not on the last line):
1581 ... >>> for x in range(10): # doctest: +ELLIPSIS
1582 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1583 ... 0 1 2...9
1584 ... '''
1585 >>> test = doctest.DocTestFinder().find(f)[0]
1586 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001587 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001588
1589It is an error to have a comment of the form ``# doctest:`` that is
1590*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1591``OPTION`` is an option that has been registered with
1592`register_option`:
1593
1594 >>> # Error: Option not registered
1595 >>> s = '>>> print 12 #doctest: +BADOPTION'
1596 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1597 Traceback (most recent call last):
1598 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1599
1600 >>> # Error: No + or - prefix
1601 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1602 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1603 Traceback (most recent call last):
1604 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1605
1606It is an error to use an option directive on a line that contains no
1607source:
1608
1609 >>> s = '>>> # doctest: +ELLIPSIS'
1610 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1611 Traceback (most recent call last):
1612 ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
Georg Brandl1f05e2e2010-08-01 08:22:05 +00001613
1614 """
1615
1616 def test_unicode_output(self): r"""
1617
1618Check that unicode output works:
1619
1620 >>> u'\xe9'
1621 u'\xe9'
1622
1623If we return unicode, SpoofOut's buf variable becomes automagically
1624converted to unicode. This means all subsequent output becomes converted
1625to unicode, and if the output contains non-ascii characters that failed.
1626It used to be that this state change carried on between tests, meaning
1627tests would fail if unicode has been output previously in the testrun.
1628This test tests that this is no longer so:
1629
1630 >>> print u'abc'
1631 abc
1632
1633And then return a string with non-ascii characters:
1634
1635 >>> print u'\xe9'.encode('utf-8')
1636 é
1637
1638 """
1639
Tim Peters8485b562004-08-04 18:46:34 +00001640
1641def test_testsource(): r"""
1642Unit tests for `testsource()`.
1643
1644The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001645test with that name in that module, and converts it to a script. The
1646example code is converted to regular Python code. The surrounding
1647words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001648
1649 >>> import test.test_doctest
1650 >>> name = 'test.test_doctest.sample_func'
1651 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001652 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001653 #
Tim Peters8485b562004-08-04 18:46:34 +00001654 print sample_func(22)
1655 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001656 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001657 #
Edward Lopera5db6002004-08-12 02:41:30 +00001658 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001659 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001660
1661 >>> name = 'test.test_doctest.SampleNewStyleClass'
1662 >>> print doctest.testsource(test.test_doctest, name)
1663 print '1\n2\n3'
1664 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001665 ## 1
1666 ## 2
1667 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001668 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001669
1670 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1671 >>> print doctest.testsource(test.test_doctest, name)
1672 print SampleClass.a_classmethod(10)
1673 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001674 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001675 print SampleClass(0).a_classmethod(10)
1676 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001677 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001678 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001679"""
1680
1681def test_debug(): r"""
1682
1683Create a docstring that we want to debug:
1684
1685 >>> s = '''
1686 ... >>> x = 12
1687 ... >>> print x
1688 ... 12
1689 ... '''
1690
1691Create some fake stdin input, to feed to the debugger:
1692
1693 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001694 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001695 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001696
1697Run the debugger on the docstring, and then restore sys.stdin.
1698
Edward Loper2de91ba2004-08-27 02:07:46 +00001699 >>> try: doctest.debug_src(s)
1700 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001702 (Pdb) next
1703 12
Tim Peters8485b562004-08-04 18:46:34 +00001704 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001705 > <string>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001706 (Pdb) print x
1707 12
1708 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001709
1710"""
1711
Jim Fulton356fd192004-08-09 11:34:47 +00001712def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001713 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001714
Tim Peters413ced62004-08-09 15:43:47 +00001715 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001716 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001717 you use it. The doctest module changes sys.stdout so that it can
1718 capture program output. It also temporarily replaces pdb.set_trace
1719 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001720 see debugger output.
1721
1722 >>> doc = '''
1723 ... >>> x = 42
Florent Xicluna80800d32010-10-14 21:46:04 +00001724 ... >>> raise Exception('clé')
1725 ... Traceback (most recent call last):
1726 ... Exception: clé
Jim Fulton356fd192004-08-09 11:34:47 +00001727 ... >>> import pdb; pdb.set_trace()
1728 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001729 >>> parser = doctest.DocTestParser()
Florent Xiclunab67660f2010-10-14 21:10:45 +00001730 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001731 >>> runner = doctest.DocTestRunner(verbose=False)
1732
1733 To demonstrate this, we'll create a fake standard input that
1734 captures our debugger input:
1735
1736 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001737 >>> real_stdin = sys.stdin
1738 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001739 ... 'print x', # print data defined by the example
1740 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001741 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001742
Edward Loper2de91ba2004-08-27 02:07:46 +00001743 >>> try: runner.run(test)
1744 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001745 --Return--
Florent Xicluna80800d32010-10-14 21:46:04 +00001746 > <doctest foo-bär@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001747 -> import pdb; pdb.set_trace()
1748 (Pdb) print x
1749 42
1750 (Pdb) continue
Florent Xicluna80800d32010-10-14 21:46:04 +00001751 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001752
1753 You can also put pdb.set_trace in a function called from a test:
1754
1755 >>> def calls_set_trace():
1756 ... y=2
1757 ... import pdb; pdb.set_trace()
1758
1759 >>> doc = '''
1760 ... >>> x=1
1761 ... >>> calls_set_trace()
1762 ... '''
Florent Xiclunab67660f2010-10-14 21:10:45 +00001763 >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001764 >>> real_stdin = sys.stdin
1765 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001766 ... 'print y', # print data defined in the function
1767 ... 'up', # out of function
1768 ... 'print x', # print data defined by the example
1769 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001770 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001771
Tim Peters50c6bdb2004-11-08 22:07:37 +00001772 >>> try:
1773 ... runner.run(test)
1774 ... finally:
1775 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001776 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001777 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1778 -> import pdb; pdb.set_trace()
1779 (Pdb) print y
1780 2
1781 (Pdb) up
Florent Xiclunab67660f2010-10-14 21:10:45 +00001782 > <doctest foo-bär@baz[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001783 -> calls_set_trace()
1784 (Pdb) print x
1785 1
1786 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001787 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001788
1789 During interactive debugging, source code is shown, even for
1790 doctest examples:
1791
1792 >>> doc = '''
1793 ... >>> def f(x):
1794 ... ... g(x*2)
1795 ... >>> def g(x):
1796 ... ... print x+3
1797 ... ... import pdb; pdb.set_trace()
1798 ... >>> f(3)
1799 ... '''
Florent Xiclunab67660f2010-10-14 21:10:45 +00001800 >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001801 >>> real_stdin = sys.stdin
1802 >>> sys.stdin = _FakeInput([
1803 ... 'list', # list source from example 2
1804 ... 'next', # return from g()
1805 ... 'list', # list source from example 1
1806 ... 'next', # return from f()
1807 ... 'list', # list source from example 3
1808 ... 'continue', # stop debugging
1809 ... ''])
1810 >>> try: runner.run(test)
1811 ... finally: sys.stdin = real_stdin
1812 ... # doctest: +NORMALIZE_WHITESPACE
1813 --Return--
Florent Xiclunab67660f2010-10-14 21:10:45 +00001814 > <doctest foo-bär@baz[1]>(3)g()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001815 -> import pdb; pdb.set_trace()
1816 (Pdb) list
1817 1 def g(x):
1818 2 print x+3
1819 3 -> import pdb; pdb.set_trace()
1820 [EOF]
1821 (Pdb) next
1822 --Return--
Florent Xiclunab67660f2010-10-14 21:10:45 +00001823 > <doctest foo-bär@baz[0]>(2)f()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001824 -> g(x*2)
1825 (Pdb) list
1826 1 def f(x):
1827 2 -> g(x*2)
1828 [EOF]
1829 (Pdb) next
1830 --Return--
Florent Xiclunab67660f2010-10-14 21:10:45 +00001831 > <doctest foo-bär@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001832 -> f(3)
1833 (Pdb) list
1834 1 -> f(3)
1835 [EOF]
1836 (Pdb) continue
1837 **********************************************************************
Florent Xiclunab67660f2010-10-14 21:10:45 +00001838 File "foo-bär@baz.py", line 7, in foo-bär@baz
Edward Loper2de91ba2004-08-27 02:07:46 +00001839 Failed example:
1840 f(3)
1841 Expected nothing
1842 Got:
1843 9
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001844 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001845 """
1846
Tim Peters50c6bdb2004-11-08 22:07:37 +00001847def test_pdb_set_trace_nested():
1848 """This illustrates more-demanding use of set_trace with nested functions.
1849
1850 >>> class C(object):
1851 ... def calls_set_trace(self):
1852 ... y = 1
1853 ... import pdb; pdb.set_trace()
1854 ... self.f1()
1855 ... y = 2
1856 ... def f1(self):
1857 ... x = 1
1858 ... self.f2()
1859 ... x = 2
1860 ... def f2(self):
1861 ... z = 1
1862 ... z = 2
1863
1864 >>> calls_set_trace = C().calls_set_trace
1865
1866 >>> doc = '''
1867 ... >>> a = 1
1868 ... >>> calls_set_trace()
1869 ... '''
1870 >>> parser = doctest.DocTestParser()
1871 >>> runner = doctest.DocTestRunner(verbose=False)
Florent Xiclunab67660f2010-10-14 21:10:45 +00001872 >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001873 >>> real_stdin = sys.stdin
1874 >>> sys.stdin = _FakeInput([
1875 ... 'print y', # print data defined in the function
1876 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z',
1877 ... 'up', 'print x',
1878 ... 'up', 'print y',
1879 ... 'up', 'print foo',
1880 ... 'continue', # stop debugging
1881 ... ''])
1882
1883 >>> try:
1884 ... runner.run(test)
1885 ... finally:
1886 ... sys.stdin = real_stdin
1887 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1888 -> self.f1()
1889 (Pdb) print y
1890 1
1891 (Pdb) step
1892 --Call--
1893 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1894 -> def f1(self):
1895 (Pdb) step
1896 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1897 -> x = 1
1898 (Pdb) step
1899 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1900 -> self.f2()
1901 (Pdb) step
1902 --Call--
1903 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1904 -> def f2(self):
1905 (Pdb) step
1906 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1907 -> z = 1
1908 (Pdb) step
1909 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1910 -> z = 2
1911 (Pdb) print z
1912 1
1913 (Pdb) up
1914 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1915 -> self.f2()
1916 (Pdb) print x
1917 1
1918 (Pdb) up
1919 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1920 -> self.f1()
1921 (Pdb) print y
1922 1
1923 (Pdb) up
Florent Xiclunab67660f2010-10-14 21:10:45 +00001924 > <doctest foo-bär@baz[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001925 -> calls_set_trace()
1926 (Pdb) print foo
1927 *** NameError: name 'foo' is not defined
1928 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001929 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001930"""
1931
Tim Peters19397e52004-08-06 22:02:59 +00001932def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001933 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001934
1935 We create a Suite by providing a module. A module can be provided
1936 by passing a module object:
1937
1938 >>> import unittest
1939 >>> import test.sample_doctest
1940 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1941 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001942 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001943
1944 We can also supply the module by name:
1945
1946 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1947 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001948 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001949
1950 We can use the current module:
1951
1952 >>> suite = test.sample_doctest.test_suite()
1953 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001954 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001955
1956 We can supply global variables. If we pass globs, they will be
1957 used instead of the module globals. Here we'll pass an empty
1958 globals, triggering an extra error:
1959
1960 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1961 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001962 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001963
1964 Alternatively, we can provide extra globals. Here we'll make an
1965 error go away by providing an extra global variable:
1966
1967 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1968 ... extraglobs={'y': 1})
1969 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001970 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001971
1972 You can pass option flags. Here we'll cause an extra error
1973 by disabling the blank-line feature:
1974
1975 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001976 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001977 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001978 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001979
Tim Peters1e277ee2004-08-07 05:37:52 +00001980 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001981
Jim Fultonf54bad42004-08-28 14:57:56 +00001982 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001983 ... import test.test_doctest
1984 ... test.test_doctest.sillySetup = True
1985
Jim Fultonf54bad42004-08-28 14:57:56 +00001986 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001987 ... import test.test_doctest
1988 ... del test.test_doctest.sillySetup
1989
1990 Here, we installed a silly variable that the test expects:
1991
1992 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1993 ... setUp=setUp, tearDown=tearDown)
1994 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001995 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001996
1997 But the tearDown restores sanity:
1998
1999 >>> import test.test_doctest
2000 >>> test.test_doctest.sillySetup
2001 Traceback (most recent call last):
2002 ...
2003 AttributeError: 'module' object has no attribute 'sillySetup'
2004
Jim Fultonf54bad42004-08-28 14:57:56 +00002005 The setUp and tearDown funtions are passed test objects. Here
2006 we'll use the setUp function to supply the missing variable y:
2007
2008 >>> def setUp(test):
2009 ... test.globs['y'] = 1
2010
2011 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2012 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002013 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002014
2015 Here, we didn't need to use a tearDown function because we
2016 modified the test globals, which are a copy of the
2017 sample_doctest module dictionary. The test globals are
2018 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002019 """
2020
2021def test_DocFileSuite():
2022 """We can test tests found in text files using a DocFileSuite.
2023
2024 We create a suite by providing the names of one or more text
2025 files that include examples:
2026
2027 >>> import unittest
2028 >>> suite = doctest.DocFileSuite('test_doctest.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002029 ... 'test_doctest2.txt',
2030 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002031 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002032 <unittest.result.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002033
2034 The test files are looked for in the directory containing the
2035 calling module. A package keyword argument can be provided to
2036 specify a different relative location.
2037
2038 >>> import unittest
2039 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2040 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002041 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002042 ... package='test')
2043 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002044 <unittest.result.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002045
Brett Cannon43e53f82007-11-21 00:47:36 +00002046 Support for using a package's __loader__.get_data() is also
2047 provided.
2048
2049 >>> import unittest, pkgutil, test
Brett Cannoneaa2c982007-11-23 00:06:51 +00002050 >>> added_loader = False
Brett Cannon43e53f82007-11-21 00:47:36 +00002051 >>> if not hasattr(test, '__loader__'):
2052 ... test.__loader__ = pkgutil.get_loader(test)
2053 ... added_loader = True
2054 >>> try:
2055 ... suite = doctest.DocFileSuite('test_doctest.txt',
2056 ... 'test_doctest2.txt',
2057 ... 'test_doctest4.txt',
2058 ... package='test')
2059 ... suite.run(unittest.TestResult())
2060 ... finally:
Brett Cannon9db1d5a2007-11-21 00:58:03 +00002061 ... if added_loader:
2062 ... del test.__loader__
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002063 <unittest.result.TestResult run=3 errors=0 failures=3>
Brett Cannon43e53f82007-11-21 00:47:36 +00002064
Edward Loper0273f5b2004-09-18 20:27:04 +00002065 '/' should be used as a path separator. It will be converted
2066 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002067
2068 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2069 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002070 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002071
Edward Loper0273f5b2004-09-18 20:27:04 +00002072 If DocFileSuite is used from an interactive session, then files
2073 are resolved relative to the directory of sys.argv[0]:
2074
Christian Heimesc756d002007-11-27 21:34:01 +00002075 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002076 >>> save_argv = sys.argv
2077 >>> sys.argv = [test.test_doctest.__file__]
2078 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimesc756d002007-11-27 21:34:01 +00002079 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002080 >>> sys.argv = save_argv
2081
Edward Loper052d0cd2004-09-19 17:19:33 +00002082 By setting `module_relative=False`, os-specific paths may be
2083 used (including absolute paths and paths relative to the
2084 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002085
2086 >>> # Get the absolute path of the test package.
2087 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2088 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2089
2090 >>> # Use it to find the absolute path of test_doctest.txt.
2091 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2092
Edward Loper052d0cd2004-09-19 17:19:33 +00002093 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002094 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002095 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002096
Edward Loper052d0cd2004-09-19 17:19:33 +00002097 It is an error to specify `package` when `module_relative=False`:
2098
2099 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2100 ... package='test')
2101 Traceback (most recent call last):
2102 ValueError: Package may only be specified for module-relative paths.
2103
Tim Peters19397e52004-08-06 22:02:59 +00002104 You can specify initial global variables:
2105
2106 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2107 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002108 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002109 ... globs={'favorite_color': 'blue'})
2110 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002111 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002112
2113 In this case, we supplied a missing favorite color. You can
2114 provide doctest options:
2115
2116 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2117 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002118 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002119 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2120 ... globs={'favorite_color': 'blue'})
2121 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002122 <unittest.result.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002123
2124 And, you can provide setUp and tearDown functions:
2125
Jim Fultonf54bad42004-08-28 14:57:56 +00002126 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002127 ... import test.test_doctest
2128 ... test.test_doctest.sillySetup = True
2129
Jim Fultonf54bad42004-08-28 14:57:56 +00002130 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002131 ... import test.test_doctest
2132 ... del test.test_doctest.sillySetup
2133
2134 Here, we installed a silly variable that the test expects:
2135
2136 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2137 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002138 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002139 ... setUp=setUp, tearDown=tearDown)
2140 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002141 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002142
2143 But the tearDown restores sanity:
2144
2145 >>> import test.test_doctest
2146 >>> test.test_doctest.sillySetup
2147 Traceback (most recent call last):
2148 ...
2149 AttributeError: 'module' object has no attribute 'sillySetup'
2150
Jim Fultonf54bad42004-08-28 14:57:56 +00002151 The setUp and tearDown funtions are passed test objects.
2152 Here, we'll use a setUp function to set the favorite color in
2153 test_doctest.txt:
2154
2155 >>> def setUp(test):
2156 ... test.globs['favorite_color'] = 'blue'
2157
2158 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2159 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002160 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002161
2162 Here, we didn't need to use a tearDown function because we
2163 modified the test globals. The test globals are
2164 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002165
Fred Drake7c404a42004-12-21 23:46:34 +00002166 Tests in a file run using `DocFileSuite` can also access the
2167 `__file__` global, which is set to the name of the file
2168 containing the tests:
2169
2170 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2171 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002172 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002173
George Yoshidaf3c65de2006-05-28 16:39:09 +00002174 If the tests contain non-ASCII characters, we have to specify which
2175 encoding the file is encoded with. We do so by using the `encoding`
2176 parameter:
2177
2178 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2179 ... 'test_doctest2.txt',
2180 ... 'test_doctest4.txt',
2181 ... encoding='utf-8')
2182 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002183 <unittest.result.TestResult run=3 errors=0 failures=2>
George Yoshidaf3c65de2006-05-28 16:39:09 +00002184
Jim Fultonf54bad42004-08-28 14:57:56 +00002185 """
Tim Peters19397e52004-08-06 22:02:59 +00002186
Jim Fulton07a349c2004-08-22 14:10:00 +00002187def test_trailing_space_in_test():
2188 """
Tim Petersa7def722004-08-23 22:13:22 +00002189 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002190
Jim Fulton07a349c2004-08-22 14:10:00 +00002191 >>> x, y = 'foo', ''
2192 >>> print x, y
2193 foo \n
2194 """
Tim Peters19397e52004-08-06 22:02:59 +00002195
Jim Fultonf54bad42004-08-28 14:57:56 +00002196
2197def test_unittest_reportflags():
2198 """Default unittest reporting flags can be set to control reporting
2199
2200 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2201 only the first failure of each test. First, we'll look at the
2202 output without the flag. The file test_doctest.txt file has two
2203 tests. They both fail if blank lines are disabled:
2204
2205 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2206 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2207 >>> import unittest
2208 >>> result = suite.run(unittest.TestResult())
2209 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2210 Traceback ...
2211 Failed example:
2212 favorite_color
2213 ...
2214 Failed example:
2215 if 1:
2216 ...
2217
2218 Note that we see both failures displayed.
2219
2220 >>> old = doctest.set_unittest_reportflags(
2221 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2222
2223 Now, when we run the test:
2224
2225 >>> result = suite.run(unittest.TestResult())
2226 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2227 Traceback ...
2228 Failed example:
2229 favorite_color
2230 Exception raised:
2231 ...
2232 NameError: name 'favorite_color' is not defined
2233 <BLANKLINE>
2234 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002235
Jim Fultonf54bad42004-08-28 14:57:56 +00002236 We get only the first failure.
2237
2238 If we give any reporting options when we set up the tests,
2239 however:
2240
2241 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2242 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2243
2244 Then the default eporting options are ignored:
2245
2246 >>> result = suite.run(unittest.TestResult())
2247 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2248 Traceback ...
2249 Failed example:
2250 favorite_color
2251 ...
2252 Failed example:
2253 if 1:
2254 print 'a'
2255 print
2256 print 'b'
2257 Differences (ndiff with -expected +actual):
2258 a
2259 - <BLANKLINE>
2260 +
2261 b
2262 <BLANKLINE>
2263 <BLANKLINE>
2264
2265
2266 Test runners can restore the formatting flags after they run:
2267
2268 >>> ignored = doctest.set_unittest_reportflags(old)
2269
2270 """
2271
Edward Loper052d0cd2004-09-19 17:19:33 +00002272def test_testfile(): r"""
2273Tests for the `testfile()` function. This function runs all the
2274doctest examples in a given file. In its simple invokation, it is
2275called with the name of a file, which is taken to be relative to the
2276calling module. The return value is (#failures, #tests).
2277
Florent Xicluna2a903b22010-02-27 13:31:23 +00002278We don't want `-v` in sys.argv for these tests.
2279
2280 >>> save_argv = sys.argv
2281 >>> if '-v' in sys.argv:
2282 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2283
2284
Edward Loper052d0cd2004-09-19 17:19:33 +00002285 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2286 **********************************************************************
2287 File "...", line 6, in test_doctest.txt
2288 Failed example:
2289 favorite_color
2290 Exception raised:
2291 ...
2292 NameError: name 'favorite_color' is not defined
2293 **********************************************************************
2294 1 items had failures:
2295 1 of 2 in test_doctest.txt
2296 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002297 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002298 >>> doctest.master = None # Reset master.
2299
2300(Note: we'll be clearing doctest.master after each call to
Florent Xicluna07627882010-03-21 01:14:24 +00002301`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002302same name.)
2303
2304Globals may be specified with the `globs` and `extraglobs` parameters:
2305
2306 >>> globs = {'favorite_color': 'blue'}
2307 >>> doctest.testfile('test_doctest.txt', globs=globs)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002308 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002309 >>> doctest.master = None # Reset master.
2310
2311 >>> extraglobs = {'favorite_color': 'red'}
2312 >>> doctest.testfile('test_doctest.txt', globs=globs,
2313 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2314 **********************************************************************
2315 File "...", line 6, in test_doctest.txt
2316 Failed example:
2317 favorite_color
2318 Expected:
2319 'blue'
2320 Got:
2321 'red'
2322 **********************************************************************
2323 1 items had failures:
2324 1 of 2 in test_doctest.txt
2325 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002326 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002327 >>> doctest.master = None # Reset master.
2328
2329The file may be made relative to a given module or package, using the
2330optional `module_relative` parameter:
2331
2332 >>> doctest.testfile('test_doctest.txt', globs=globs,
2333 ... module_relative='test')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002334 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002335 >>> doctest.master = None # Reset master.
2336
2337Verbosity can be increased with the optional `verbose` paremter:
2338
2339 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2340 Trying:
2341 favorite_color
2342 Expecting:
2343 'blue'
2344 ok
2345 Trying:
2346 if 1:
2347 print 'a'
2348 print
2349 print 'b'
2350 Expecting:
2351 a
2352 <BLANKLINE>
2353 b
2354 ok
2355 1 items passed all tests:
2356 2 tests in test_doctest.txt
2357 2 tests in 1 items.
2358 2 passed and 0 failed.
2359 Test passed.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002360 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002361 >>> doctest.master = None # Reset master.
2362
2363The name of the test may be specified with the optional `name`
2364parameter:
2365
2366 >>> doctest.testfile('test_doctest.txt', name='newname')
2367 ... # doctest: +ELLIPSIS
2368 **********************************************************************
2369 File "...", line 6, in newname
2370 ...
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002371 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002372 >>> doctest.master = None # Reset master.
2373
2374The summary report may be supressed with the optional `report`
2375parameter:
2376
2377 >>> doctest.testfile('test_doctest.txt', report=False)
2378 ... # doctest: +ELLIPSIS
2379 **********************************************************************
2380 File "...", line 6, in test_doctest.txt
2381 Failed example:
2382 favorite_color
2383 Exception raised:
2384 ...
2385 NameError: name 'favorite_color' is not defined
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002386 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002387 >>> doctest.master = None # Reset master.
2388
2389The optional keyword argument `raise_on_error` can be used to raise an
2390exception on the first error (which may be useful for postmortem
2391debugging):
2392
2393 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2394 ... # doctest: +ELLIPSIS
2395 Traceback (most recent call last):
2396 UnexpectedException: ...
2397 >>> doctest.master = None # Reset master.
George Yoshidaf3c65de2006-05-28 16:39:09 +00002398
2399If the tests contain non-ASCII characters, the tests might fail, since
2400it's unknown which encoding is used. The encoding can be specified
2401using the optional keyword argument `encoding`:
2402
2403 >>> doctest.testfile('test_doctest4.txt') # doctest: +ELLIPSIS
2404 **********************************************************************
2405 File "...", line 7, in test_doctest4.txt
2406 Failed example:
2407 u'...'
2408 Expected:
2409 u'f\xf6\xf6'
2410 Got:
2411 u'f\xc3\xb6\xc3\xb6'
2412 **********************************************************************
2413 ...
2414 **********************************************************************
2415 1 items had failures:
2416 2 of 4 in test_doctest4.txt
2417 ***Test Failed*** 2 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002418 TestResults(failed=2, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002419 >>> doctest.master = None # Reset master.
2420
2421 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002422 TestResults(failed=0, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002423 >>> doctest.master = None # Reset master.
Florent Xicluna2a903b22010-02-27 13:31:23 +00002424
2425Switch the module encoding to 'utf-8' to test the verbose output without
2426bothering with the current sys.stdout encoding.
2427
2428 >>> doctest._encoding, saved_encoding = 'utf-8', doctest._encoding
2429 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2430 Trying:
2431 u'föö'
2432 Expecting:
2433 u'f\xf6\xf6'
2434 ok
2435 Trying:
2436 u'bÄ…r'
2437 Expecting:
2438 u'b\u0105r'
2439 ok
2440 Trying:
2441 'föö'
2442 Expecting:
2443 'f\xc3\xb6\xc3\xb6'
2444 ok
2445 Trying:
2446 'bÄ…r'
2447 Expecting:
2448 'b\xc4\x85r'
2449 ok
2450 1 items passed all tests:
2451 4 tests in test_doctest4.txt
2452 4 tests in 1 items.
2453 4 passed and 0 failed.
2454 Test passed.
2455 TestResults(failed=0, attempted=4)
2456 >>> doctest._encoding = saved_encoding
2457 >>> doctest.master = None # Reset master.
2458 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002459"""
2460
Tim Petersa7def722004-08-23 22:13:22 +00002461# old_test1, ... used to live in doctest.py, but cluttered it. Note
2462# that these use the deprecated doctest.Tester, so should go away (or
2463# be rewritten) someday.
2464
Tim Petersa7def722004-08-23 22:13:22 +00002465def old_test1(): r"""
2466>>> from doctest import Tester
2467>>> t = Tester(globs={'x': 42}, verbose=0)
2468>>> t.runstring(r'''
2469... >>> x = x * 2
2470... >>> print x
2471... 42
2472... ''', 'XYZ')
2473**********************************************************************
2474Line 3, in XYZ
2475Failed example:
2476 print x
2477Expected:
2478 42
2479Got:
2480 84
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002481TestResults(failed=1, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002482>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002483TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002484>>> t.summarize()
2485**********************************************************************
24861 items had failures:
2487 1 of 2 in XYZ
2488***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002489TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002490>>> t.summarize(verbose=1)
24911 items passed all tests:
2492 2 tests in example2
2493**********************************************************************
24941 items had failures:
2495 1 of 2 in XYZ
24964 tests in 2 items.
24973 passed and 1 failed.
2498***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002499TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002500"""
2501
2502def old_test2(): r"""
2503 >>> from doctest import Tester
2504 >>> t = Tester(globs={}, verbose=1)
2505 >>> test = r'''
2506 ... # just an example
2507 ... >>> x = 1 + 2
2508 ... >>> x
2509 ... 3
2510 ... '''
2511 >>> t.runstring(test, "Example")
2512 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002513 Trying:
2514 x = 1 + 2
2515 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002516 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002517 Trying:
2518 x
2519 Expecting:
2520 3
Tim Petersa7def722004-08-23 22:13:22 +00002521 ok
2522 0 of 2 examples failed in string Example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002523 TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002524"""
2525
2526def old_test3(): r"""
2527 >>> from doctest import Tester
2528 >>> t = Tester(globs={}, verbose=0)
2529 >>> def _f():
2530 ... '''Trivial docstring example.
2531 ... >>> assert 2 == 2
2532 ... '''
2533 ... return 32
2534 ...
2535 >>> t.rundoc(_f) # expect 0 failures in 1 example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002536 TestResults(failed=0, attempted=1)
Tim Petersa7def722004-08-23 22:13:22 +00002537"""
2538
2539def old_test4(): """
Christian Heimesc756d002007-11-27 21:34:01 +00002540 >>> import types
2541 >>> m1 = types.ModuleType('_m1')
2542 >>> m2 = types.ModuleType('_m2')
Tim Petersa7def722004-08-23 22:13:22 +00002543 >>> test_data = \"""
2544 ... def _f():
2545 ... '''>>> assert 1 == 1
2546 ... '''
2547 ... def g():
2548 ... '''>>> assert 2 != 1
2549 ... '''
2550 ... class H:
2551 ... '''>>> assert 2 > 1
2552 ... '''
2553 ... def bar(self):
2554 ... '''>>> assert 1 < 2
2555 ... '''
2556 ... \"""
2557 >>> exec test_data in m1.__dict__
2558 >>> exec test_data in m2.__dict__
2559 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2560
2561 Tests that objects outside m1 are excluded:
2562
2563 >>> from doctest import Tester
2564 >>> t = Tester(globs={}, verbose=0)
2565 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002566 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002567
2568 Once more, not excluding stuff outside m1:
2569
2570 >>> t = Tester(globs={}, verbose=0)
2571 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002572 TestResults(failed=0, attempted=8)
Tim Petersa7def722004-08-23 22:13:22 +00002573
2574 The exclusion of objects from outside the designated module is
2575 meant to be invoked automagically by testmod.
2576
2577 >>> doctest.testmod(m1, verbose=False)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002578 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002579"""
2580
Tim Peters8485b562004-08-04 18:46:34 +00002581######################################################################
2582## Main
2583######################################################################
2584
2585def test_main():
2586 # Check the doctest cases in doctest itself:
2587 test_support.run_doctest(doctest, verbosity=True)
Florent Xicluna07627882010-03-21 01:14:24 +00002588
Tim Peters8485b562004-08-04 18:46:34 +00002589 from test import test_doctest
Florent Xicluna6257a7b2010-03-31 22:01:03 +00002590
2591 # Ignore all warnings about the use of class Tester in this module.
2592 deprecations = [("class Tester is deprecated", DeprecationWarning)]
2593 if sys.py3kwarning:
2594 deprecations += [("backquote not supported", SyntaxWarning),
2595 ("execfile.. not supported", DeprecationWarning)]
2596 with test_support.check_warnings(*deprecations):
Florent Xicluna07627882010-03-21 01:14:24 +00002597 # Check the doctest cases defined here:
2598 test_support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002599
Victor Stinneredb9f872010-04-27 21:51:26 +00002600import sys
Tim Peters8485b562004-08-04 18:46:34 +00002601def test_coverage(coverdir):
Victor Stinneredb9f872010-04-27 21:51:26 +00002602 trace = test_support.import_module('trace')
Tim Peters8485b562004-08-04 18:46:34 +00002603 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2604 trace=0, count=1)
2605 tracer.run('reload(doctest); test_main()')
2606 r = tracer.results()
2607 print 'Writing coverage results...'
2608 r.write_results(show_missing=True, summary=True,
2609 coverdir=coverdir)
2610
2611if __name__ == '__main__':
2612 if '-c' in sys.argv:
2613 test_coverage('/tmp/doctest.cover')
2614 else:
2615 test_main()