blob: 53073958d81c0183ba431dd7bb076ead748516eb [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Barry Warsaw04f357c2002-07-23 19:04:11 +00005from test import test_support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Tim Petersa7def722004-08-23 22:13:22 +00007import warnings
Tim Peters8485b562004-08-04 18:46:34 +00008
9######################################################################
10## Sample Objects (used by test cases)
11######################################################################
12
13def sample_func(v):
14 """
Tim Peters19397e52004-08-06 22:02:59 +000015 Blah blah
16
Guido van Rossum7131f842007-02-09 20:13:25 +000017 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000018 44
Tim Peters19397e52004-08-06 22:02:59 +000019
20 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000021 """
22 return v+v
23
24class SampleClass:
25 """
Guido van Rossum7131f842007-02-09 20:13:25 +000026 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000027 1
Edward Loper4ae900f2004-09-21 03:20:34 +000028
29 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
30 >>>
31 ...
32
33 Multiline example:
34 >>> sc = SampleClass(3)
35 >>> for i in range(10):
36 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000037 ... print(' ', sc.get(), sep='', end='')
38 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000039 """
40 def __init__(self, val):
41 """
Guido van Rossum7131f842007-02-09 20:13:25 +000042 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000043 12
44 """
45 self.val = val
46
47 def double(self):
48 """
Guido van Rossum7131f842007-02-09 20:13:25 +000049 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000050 24
51 """
52 return SampleClass(self.val + self.val)
53
54 def get(self):
55 """
Guido van Rossum7131f842007-02-09 20:13:25 +000056 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000057 -5
58 """
59 return self.val
60
61 def a_staticmethod(v):
62 """
Guido van Rossum7131f842007-02-09 20:13:25 +000063 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000064 11
65 """
66 return v+1
67 a_staticmethod = staticmethod(a_staticmethod)
68
69 def a_classmethod(cls, v):
70 """
Guido van Rossum7131f842007-02-09 20:13:25 +000071 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000072 12
Guido van Rossum7131f842007-02-09 20:13:25 +000073 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000074 12
75 """
76 return v+2
77 a_classmethod = classmethod(a_classmethod)
78
79 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000080 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000081 22
82 """)
83
84 class NestedClass:
85 """
86 >>> x = SampleClass.NestedClass(5)
87 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000088 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000089 25
90 """
91 def __init__(self, val=0):
92 """
Guido van Rossum7131f842007-02-09 20:13:25 +000093 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +000094 0
95 """
96 self.val = val
97 def square(self):
98 return SampleClass.NestedClass(self.val*self.val)
99 def get(self):
100 return self.val
101
102class SampleNewStyleClass(object):
103 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000104 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000105 1
106 2
107 3
108 """
109 def __init__(self, val):
110 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000111 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000112 12
113 """
114 self.val = val
115
116 def double(self):
117 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000118 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000119 24
120 """
121 return SampleNewStyleClass(self.val + self.val)
122
123 def get(self):
124 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000125 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000126 -5
127 """
128 return self.val
129
130######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000131## Fake stdin (for testing interactive debugging)
132######################################################################
133
134class _FakeInput:
135 """
136 A fake input stream for pdb's interactive debugger. Whenever a
137 line is read, print it (to simulate the user typing it), and then
138 return it. The set of lines to return is specified in the
139 constructor; they should not have trailing newlines.
140 """
141 def __init__(self, lines):
142 self.lines = lines
143
144 def readline(self):
145 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000146 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000147 return line+'\n'
148
149######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000150## Test Cases
151######################################################################
152
153def test_Example(): r"""
154Unit tests for the `Example` class.
155
Edward Lopera6b68322004-08-26 00:05:43 +0000156Example is a simple container class that holds:
157 - `source`: A source string.
158 - `want`: An expected output string.
159 - `exc_msg`: An expected exception message string (or None if no
160 exception is expected).
161 - `lineno`: A line number (within the docstring).
162 - `indent`: The example's indentation in the input string.
163 - `options`: An option dictionary, mapping option flags to True or
164 False.
Tim Peters8485b562004-08-04 18:46:34 +0000165
Edward Lopera6b68322004-08-26 00:05:43 +0000166These attributes are set by the constructor. `source` and `want` are
167required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000168
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000169 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000170 >>> (example.source, example.want, example.exc_msg,
171 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000172 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000173
174The first three attributes (`source`, `want`, and `exc_msg`) may be
175specified positionally; the remaining arguments should be specified as
176keyword arguments:
177
178 >>> exc_msg = 'IndexError: pop from an empty list'
179 >>> example = doctest.Example('[].pop()', '', exc_msg,
180 ... lineno=5, indent=4,
181 ... options={doctest.ELLIPSIS: True})
182 >>> (example.source, example.want, example.exc_msg,
183 ... example.lineno, example.indent, example.options)
184 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
185
186The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000187
Tim Petersbb431472004-08-09 03:51:46 +0000188 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000189 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000190 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000191 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000192
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000193 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000194 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000195 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000196
Tim Petersbb431472004-08-09 03:51:46 +0000197 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000198 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000199 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000200 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000201
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000202 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000203 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000204 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000205
Edward Lopera6b68322004-08-26 00:05:43 +0000206 Empty source string (which should never appear in real examples)
207 >>> e = doctest.Example('', '')
208 >>> e.source, e.want
209 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000210
Edward Lopera6b68322004-08-26 00:05:43 +0000211The constructor normalizes the `want` string to end in a newline,
212unless it's the empty string:
213
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000214 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000215 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000216 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000217
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000218 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000219 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000220 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000221
Edward Lopera6b68322004-08-26 00:05:43 +0000222 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000223 >>> e.source, e.want
224 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000225
226The constructor normalizes the `exc_msg` string to end in a newline,
227unless it's `None`:
228
229 Message spans one line
230 >>> exc_msg = 'IndexError: pop from an empty list'
231 >>> e = doctest.Example('[].pop()', '', exc_msg)
232 >>> e.exc_msg
233 'IndexError: pop from an empty list\n'
234
235 >>> exc_msg = 'IndexError: pop from an empty list\n'
236 >>> e = doctest.Example('[].pop()', '', exc_msg)
237 >>> e.exc_msg
238 'IndexError: pop from an empty list\n'
239
240 Message spans multiple lines
241 >>> exc_msg = 'ValueError: 1\n 2'
242 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
243 >>> e.exc_msg
244 'ValueError: 1\n 2\n'
245
246 >>> exc_msg = 'ValueError: 1\n 2\n'
247 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
248 >>> e.exc_msg
249 'ValueError: 1\n 2\n'
250
251 Empty (but non-None) exception message (which should never appear
252 in real examples)
253 >>> exc_msg = ''
254 >>> e = doctest.Example('raise X()', '', exc_msg)
255 >>> e.exc_msg
256 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000257"""
258
259def test_DocTest(): r"""
260Unit tests for the `DocTest` class.
261
262DocTest is a collection of examples, extracted from a docstring, along
263with information about where the docstring comes from (a name,
264filename, and line number). The docstring is parsed by the `DocTest`
265constructor:
266
267 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000268 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000269 ... 12
270 ...
271 ... Non-example text.
272 ...
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000273 ... >>> print('another\example')
Tim Peters8485b562004-08-04 18:46:34 +0000274 ... another
275 ... example
276 ... '''
277 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000278 >>> parser = doctest.DocTestParser()
279 >>> test = parser.get_doctest(docstring, globs, 'some_test',
280 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000281 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000282 <DocTest some_test from some_file:20 (2 examples)>
283 >>> len(test.examples)
284 2
285 >>> e1, e2 = test.examples
286 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000287 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000288 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000289 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000290
291Source information (name, filename, and line number) is available as
292attributes on the doctest object:
293
294 >>> (test.name, test.filename, test.lineno)
295 ('some_test', 'some_file', 20)
296
297The line number of an example within its containing file is found by
298adding the line number of the example and the line number of its
299containing test:
300
301 >>> test.lineno + e1.lineno
302 21
303 >>> test.lineno + e2.lineno
304 26
305
306If the docstring contains inconsistant leading whitespace in the
307expected output of an example, then `DocTest` will raise a ValueError:
308
309 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000310 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000311 ... bad
312 ... indentation
313 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000314 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000315 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000316 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000317
318If the docstring contains inconsistent leading whitespace on
319continuation lines, then `DocTest` will raise a ValueError:
320
321 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000322 ... >>> print(('bad indentation',
323 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000324 ... ('bad', 'indentation')
325 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000326 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000327 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000328 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000329
330If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
331will raise a ValueError:
332
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000333 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000334 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000335 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000336 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000337
338If there's no blank space after a PS2 prompt ('...'), then `DocTest`
339will raise a ValueError:
340
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000341 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000342 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000343 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000344 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000345
Tim Peters8485b562004-08-04 18:46:34 +0000346"""
347
Tim Peters8485b562004-08-04 18:46:34 +0000348def test_DocTestFinder(): r"""
349Unit tests for the `DocTestFinder` class.
350
351DocTestFinder is used to extract DocTests from an object's docstring
352and the docstrings of its contained objects. It can be used with
353modules, functions, classes, methods, staticmethods, classmethods, and
354properties.
355
356Finding Tests in Functions
357~~~~~~~~~~~~~~~~~~~~~~~~~~
358For a function whose docstring contains examples, DocTestFinder.find()
359will return a single test (for that function's docstring):
360
Tim Peters8485b562004-08-04 18:46:34 +0000361 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000362
363We'll simulate a __file__ attr that ends in pyc:
364
365 >>> import test.test_doctest
366 >>> old = test.test_doctest.__file__
367 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
368
Tim Peters8485b562004-08-04 18:46:34 +0000369 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000370
Guido van Rossum7131f842007-02-09 20:13:25 +0000371 >>> print(tests) # doctest: +ELLIPSIS
Tim Petersa7def722004-08-23 22:13:22 +0000372 [<DocTest sample_func from ...:13 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000373
Tim Peters4de7c5c2004-08-23 22:38:05 +0000374The exact name depends on how test_doctest was invoked, so allow for
375leading path components.
376
377 >>> tests[0].filename # doctest: +ELLIPSIS
378 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000379
380 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000381
Jim Fulton07a349c2004-08-22 14:10:00 +0000382
Tim Peters8485b562004-08-04 18:46:34 +0000383 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000384 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000385 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000386
Edward Loper32ddbf72004-09-13 05:47:24 +0000387By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000388
389 >>> def no_docstring(v):
390 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000391 >>> finder.find(no_docstring)
392 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000393
394However, the optional argument `exclude_empty` to the DocTestFinder
395constructor can be used to exclude tests for objects with empty
396docstrings:
397
398 >>> def no_docstring(v):
399 ... pass
400 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
401 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000402 []
403
404If the function has a docstring with no examples, then a test with no
405examples is returned. (This lets `DocTestRunner` collect statistics
406about which functions have no tests -- but is that useful? And should
407an empty test also be created when there's no docstring?)
408
409 >>> def no_examples(v):
410 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000411 >>> finder.find(no_examples) # doctest: +ELLIPSIS
412 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000413
414Finding Tests in Classes
415~~~~~~~~~~~~~~~~~~~~~~~~
416For a class, DocTestFinder will create a test for the class's
417docstring, and will recursively explore its contents, including
418methods, classmethods, staticmethods, properties, and nested classes.
419
420 >>> finder = doctest.DocTestFinder()
421 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000422 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000423 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000424 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000425 3 SampleClass.NestedClass
426 1 SampleClass.NestedClass.__init__
427 1 SampleClass.__init__
428 2 SampleClass.a_classmethod
429 1 SampleClass.a_property
430 1 SampleClass.a_staticmethod
431 1 SampleClass.double
432 1 SampleClass.get
433
434New-style classes are also supported:
435
436 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000437 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000438 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000439 1 SampleNewStyleClass
440 1 SampleNewStyleClass.__init__
441 1 SampleNewStyleClass.double
442 1 SampleNewStyleClass.get
443
444Finding Tests in Modules
445~~~~~~~~~~~~~~~~~~~~~~~~
446For a module, DocTestFinder will create a test for the class's
447docstring, and will recursively explore its contents, including
448functions, classes, and the `__test__` dictionary, if it exists:
449
450 >>> # A module
451 >>> import new
452 >>> m = new.module('some_module')
453 >>> def triple(val):
454 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000455 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000456 ... 33
457 ... '''
458 ... return val*3
459 >>> m.__dict__.update({
460 ... 'sample_func': sample_func,
461 ... 'SampleClass': SampleClass,
462 ... '__doc__': '''
463 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000464 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000465 ... module
466 ... ''',
467 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000468 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000469 ... 'c': triple}})
470
471 >>> finder = doctest.DocTestFinder()
472 >>> # Use module=test.test_doctest, to prevent doctest from
473 >>> # ignoring the objects since they weren't defined in m.
474 >>> import test.test_doctest
475 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000476 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000477 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000478 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000479 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000480 3 some_module.SampleClass.NestedClass
481 1 some_module.SampleClass.NestedClass.__init__
482 1 some_module.SampleClass.__init__
483 2 some_module.SampleClass.a_classmethod
484 1 some_module.SampleClass.a_property
485 1 some_module.SampleClass.a_staticmethod
486 1 some_module.SampleClass.double
487 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000488 1 some_module.__test__.c
489 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000490 1 some_module.sample_func
491
492Duplicate Removal
493~~~~~~~~~~~~~~~~~
494If a single object is listed twice (under different names), then tests
495will only be generated for it once:
496
Tim Petersf3f57472004-08-08 06:11:48 +0000497 >>> from test import doctest_aliases
Edward Loper32ddbf72004-09-13 05:47:24 +0000498 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000499 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000500 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000501 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000502 test.doctest_aliases.TwoNames
503
504 TwoNames.f and TwoNames.g are bound to the same object.
505 We can't guess which will be found in doctest's traversal of
506 TwoNames.__dict__ first, so we have to allow for either.
507
508 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000509 True
510
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000511Empty Tests
512~~~~~~~~~~~
513By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000514
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000515 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000516 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000517 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000518 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000519 3 SampleClass.NestedClass
520 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000521 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000522 2 SampleClass.a_classmethod
523 1 SampleClass.a_property
524 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000525 1 SampleClass.double
526 1 SampleClass.get
527
528By default, that excluded objects with no doctests. exclude_empty=False
529tells it to include (empty) tests for objects with no doctests. This feature
530is really to support backward compatibility in what doctest.master.summarize()
531displays.
532
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000533 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000534 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000535 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000536 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000537 3 SampleClass.NestedClass
538 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000539 0 SampleClass.NestedClass.get
540 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000541 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000542 2 SampleClass.a_classmethod
543 1 SampleClass.a_property
544 1 SampleClass.a_staticmethod
545 1 SampleClass.double
546 1 SampleClass.get
547
Tim Peters8485b562004-08-04 18:46:34 +0000548Turning off Recursion
549~~~~~~~~~~~~~~~~~~~~~
550DocTestFinder can be told not to look for tests in contained objects
551using the `recurse` flag:
552
553 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000554 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000555 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000556 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000557
558Line numbers
559~~~~~~~~~~~~
560DocTestFinder finds the line number of each example:
561
562 >>> def f(x):
563 ... '''
564 ... >>> x = 12
565 ...
566 ... some text
567 ...
568 ... >>> # examples are not created for comments & bare prompts.
569 ... >>>
570 ... ...
571 ...
572 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000573 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000574 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000575 ... >>> x//2
576 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000577 ... '''
578 >>> test = doctest.DocTestFinder().find(f)[0]
579 >>> [e.lineno for e in test.examples]
580 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000581"""
582
Edward Loper00f8da72004-08-26 18:05:07 +0000583def test_DocTestParser(): r"""
584Unit tests for the `DocTestParser` class.
585
586DocTestParser is used to parse docstrings containing doctest examples.
587
588The `parse` method divides a docstring into examples and intervening
589text:
590
591 >>> s = '''
592 ... >>> x, y = 2, 3 # no output expected
593 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000594 ... ... print(x)
595 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000596 ... 2
597 ... 3
598 ...
599 ... Some text.
600 ... >>> x+y
601 ... 5
602 ... '''
603 >>> parser = doctest.DocTestParser()
604 >>> for piece in parser.parse(s):
605 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000606 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000607 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000608 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000609 Text: '\n'
610 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
611 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000612 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000613 Text: '\nSome text.\n'
614 Example: ('x+y\n', '5\n', 9)
615 Text: ''
616
617The `get_examples` method returns just the examples:
618
619 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000620 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000621 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000622 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000623 ('x+y\n', '5\n', 9)
624
625The `get_doctest` method creates a Test from the examples, along with the
626given arguments:
627
628 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
629 >>> (test.name, test.filename, test.lineno)
630 ('name', 'filename', 5)
631 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000632 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000633 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000634 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000635 ('x+y\n', '5\n', 9)
636"""
637
Tim Peters8485b562004-08-04 18:46:34 +0000638class test_DocTestRunner:
639 def basics(): r"""
640Unit tests for the `DocTestRunner` class.
641
642DocTestRunner is used to run DocTest test cases, and to accumulate
643statistics. Here's a simple DocTest case we can use:
644
645 >>> def f(x):
646 ... '''
647 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000648 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000649 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000650 ... >>> x//2
651 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000652 ... '''
653 >>> test = doctest.DocTestFinder().find(f)[0]
654
655The main DocTestRunner interface is the `run` method, which runs a
656given DocTest case in a given namespace (globs). It returns a tuple
657`(f,t)`, where `f` is the number of failed tests and `t` is the number
658of tried tests.
659
660 >>> doctest.DocTestRunner(verbose=False).run(test)
661 (0, 3)
662
663If any example produces incorrect output, then the test runner reports
664the failure and proceeds to the next example:
665
666 >>> def f(x):
667 ... '''
668 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000669 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000670 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000671 ... >>> x//2
672 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000673 ... '''
674 >>> test = doctest.DocTestFinder().find(f)[0]
675 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000676 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000677 Trying:
678 x = 12
679 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000680 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000681 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000682 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000683 Expecting:
684 14
Tim Peters8485b562004-08-04 18:46:34 +0000685 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000686 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000687 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000688 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000689 Expected:
690 14
691 Got:
692 12
Edward Loperaacf0832004-08-26 01:19:50 +0000693 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000694 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000695 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000696 6
Tim Peters8485b562004-08-04 18:46:34 +0000697 ok
698 (1, 3)
699"""
700 def verbose_flag(): r"""
701The `verbose` flag makes the test runner generate more detailed
702output:
703
704 >>> def f(x):
705 ... '''
706 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000707 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000708 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000709 ... >>> x//2
710 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000711 ... '''
712 >>> test = doctest.DocTestFinder().find(f)[0]
713
714 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000715 Trying:
716 x = 12
717 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000718 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000719 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000720 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000721 Expecting:
722 12
Tim Peters8485b562004-08-04 18:46:34 +0000723 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000724 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000725 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000726 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000727 6
Tim Peters8485b562004-08-04 18:46:34 +0000728 ok
729 (0, 3)
730
731If the `verbose` flag is unspecified, then the output will be verbose
732iff `-v` appears in sys.argv:
733
734 >>> # Save the real sys.argv list.
735 >>> old_argv = sys.argv
736
737 >>> # If -v does not appear in sys.argv, then output isn't verbose.
738 >>> sys.argv = ['test']
739 >>> doctest.DocTestRunner().run(test)
740 (0, 3)
741
742 >>> # If -v does appear in sys.argv, then output is verbose.
743 >>> sys.argv = ['test', '-v']
744 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000745 Trying:
746 x = 12
747 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000748 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000749 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000750 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000751 Expecting:
752 12
Tim Peters8485b562004-08-04 18:46:34 +0000753 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000754 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000755 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000756 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000757 6
Tim Peters8485b562004-08-04 18:46:34 +0000758 ok
759 (0, 3)
760
761 >>> # Restore sys.argv
762 >>> sys.argv = old_argv
763
764In the remaining examples, the test runner's verbosity will be
765explicitly set, to ensure that the test behavior is consistent.
766 """
767 def exceptions(): r"""
768Tests of `DocTestRunner`'s exception handling.
769
770An expected exception is specified with a traceback message. The
771lines between the first line and the type/value may be omitted or
772replaced with any other string:
773
774 >>> def f(x):
775 ... '''
776 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000777 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000778 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000779 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000780 ... '''
781 >>> test = doctest.DocTestFinder().find(f)[0]
782 >>> doctest.DocTestRunner(verbose=False).run(test)
783 (0, 2)
784
Edward Loper19b19582004-08-25 23:07:03 +0000785An example may not generate output before it raises an exception; if
786it does, then the traceback message will not be recognized as
787signaling an expected exception, so the example will be reported as an
788unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000789
790 >>> def f(x):
791 ... '''
792 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000793 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000794 ... pre-exception output
795 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000796 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000797 ... '''
798 >>> test = doctest.DocTestFinder().find(f)[0]
799 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000800 ... # doctest: +ELLIPSIS
801 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000802 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000803 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000804 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000805 Exception raised:
806 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000807 ZeroDivisionError: integer division or modulo by zero
Edward Loper19b19582004-08-25 23:07:03 +0000808 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000809
810Exception messages may contain newlines:
811
812 >>> def f(x):
813 ... r'''
814 ... >>> raise ValueError, 'multi\nline\nmessage'
815 ... Traceback (most recent call last):
816 ... ValueError: multi
817 ... line
818 ... message
819 ... '''
820 >>> test = doctest.DocTestFinder().find(f)[0]
821 >>> doctest.DocTestRunner(verbose=False).run(test)
822 (0, 1)
823
824If an exception is expected, but an exception with the wrong type or
825message is raised, then it is reported as a failure:
826
827 >>> def f(x):
828 ... r'''
829 ... >>> raise ValueError, 'message'
830 ... Traceback (most recent call last):
831 ... ValueError: wrong message
832 ... '''
833 >>> test = doctest.DocTestFinder().find(f)[0]
834 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000835 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000836 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000837 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000838 Failed example:
839 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000840 Expected:
841 Traceback (most recent call last):
842 ValueError: wrong message
843 Got:
844 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000845 ...
Tim Peters8485b562004-08-04 18:46:34 +0000846 ValueError: message
847 (1, 1)
848
Tim Peters1fbf9c52004-09-04 17:21:02 +0000849However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
850detail:
851
852 >>> def f(x):
853 ... r'''
854 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
855 ... Traceback (most recent call last):
856 ... ValueError: wrong message
857 ... '''
858 >>> test = doctest.DocTestFinder().find(f)[0]
859 >>> doctest.DocTestRunner(verbose=False).run(test)
860 (0, 1)
861
862But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
863
864 >>> def f(x):
865 ... r'''
866 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
867 ... Traceback (most recent call last):
868 ... TypeError: wrong type
869 ... '''
870 >>> test = doctest.DocTestFinder().find(f)[0]
871 >>> doctest.DocTestRunner(verbose=False).run(test)
872 ... # doctest: +ELLIPSIS
873 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000874 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000875 Failed example:
876 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
877 Expected:
878 Traceback (most recent call last):
879 TypeError: wrong type
880 Got:
881 Traceback (most recent call last):
882 ...
883 ValueError: message
884 (1, 1)
885
Tim Peters8485b562004-08-04 18:46:34 +0000886If an exception is raised but not expected, then it is reported as an
887unexpected exception:
888
Tim Peters8485b562004-08-04 18:46:34 +0000889 >>> def f(x):
890 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000891 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000892 ... 0
893 ... '''
894 >>> test = doctest.DocTestFinder().find(f)[0]
895 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000896 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000897 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000898 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000899 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000900 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000901 Exception raised:
902 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000903 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000904 ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000905 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000906"""
907 def optionflags(): r"""
908Tests of `DocTestRunner`'s option flag handling.
909
910Several option flags can be used to customize the behavior of the test
911runner. These are defined as module constants in doctest, and passed
912to the DocTestRunner constructor (multiple constants should be or-ed
913together).
914
915The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
916and 1/0:
917
918 >>> def f(x):
919 ... '>>> True\n1\n'
920
921 >>> # Without the flag:
922 >>> test = doctest.DocTestFinder().find(f)[0]
923 >>> doctest.DocTestRunner(verbose=False).run(test)
924 (0, 1)
925
926 >>> # With the flag:
927 >>> test = doctest.DocTestFinder().find(f)[0]
928 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
929 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000930 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000931 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000932 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000933 Failed example:
934 True
935 Expected:
936 1
937 Got:
938 True
Tim Peters8485b562004-08-04 18:46:34 +0000939 (1, 1)
940
941The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
942and the '<BLANKLINE>' marker:
943
944 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000945 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +0000946
947 >>> # Without the flag:
948 >>> test = doctest.DocTestFinder().find(f)[0]
949 >>> doctest.DocTestRunner(verbose=False).run(test)
950 (0, 1)
951
952 >>> # With the flag:
953 >>> test = doctest.DocTestFinder().find(f)[0]
954 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
955 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000956 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000957 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000958 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000959 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000960 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +0000961 Expected:
962 a
963 <BLANKLINE>
964 b
965 Got:
966 a
967 <BLANKLINE>
968 b
969 (1, 1)
970
971The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
972treated as equal:
973
974 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000975 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +0000976
977 >>> # Without the flag:
978 >>> test = doctest.DocTestFinder().find(f)[0]
979 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000980 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000981 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000982 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000983 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000984 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +0000985 Expected:
986 1 2
987 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000988 Got:
989 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000990 (1, 1)
991
992 >>> # With the flag:
993 >>> test = doctest.DocTestFinder().find(f)[0]
994 >>> flags = doctest.NORMALIZE_WHITESPACE
995 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
996 (0, 1)
997
Tim Peters026f8dc2004-08-19 16:38:58 +0000998 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +0000999 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001000 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1001 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1002
Tim Peters8485b562004-08-04 18:46:34 +00001003The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1004output to match any substring in the actual output:
1005
1006 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001007 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001008
1009 >>> # Without the flag:
1010 >>> test = doctest.DocTestFinder().find(f)[0]
1011 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001012 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001013 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001014 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001015 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001016 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001017 Expected:
1018 [0, 1, 2, ..., 14]
1019 Got:
1020 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +00001021 (1, 1)
1022
1023 >>> # With the flag:
1024 >>> test = doctest.DocTestFinder().find(f)[0]
1025 >>> flags = doctest.ELLIPSIS
1026 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1027 (0, 1)
1028
Tim Peterse594bee2004-08-22 01:47:51 +00001029 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001030
Guido van Rossume0192e52007-02-09 23:39:59 +00001031 >>> if 1:
1032 ... for i in range(100):
1033 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1034 ... print('!')
1035 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001036
Tim Peters026f8dc2004-08-19 16:38:58 +00001037 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001038
Guido van Rossume0192e52007-02-09 23:39:59 +00001039 >>> if 1: #doctest: +ELLIPSIS
1040 ... for i in range(20):
1041 ... print(i, end=' ')
1042 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001043 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001044
Tim Peters026f8dc2004-08-19 16:38:58 +00001045 Examples from the docs:
1046
Guido van Rossum805365e2007-05-07 22:24:25 +00001047 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001048 [0, 1, ..., 18, 19]
1049
Guido van Rossum805365e2007-05-07 22:24:25 +00001050 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001051 ... # doctest: +NORMALIZE_WHITESPACE
1052 [0, 1, ..., 18, 19]
1053
Thomas Wouters477c8d52006-05-27 19:21:47 +00001054The SKIP flag causes an example to be skipped entirely. I.e., the
1055example is not run. It can be useful in contexts where doctest
1056examples serve as both documentation and test cases, and an example
1057should be included for documentation purposes, but should not be
1058checked (e.g., because its output is random, or depends on resources
1059which would be unavailable.) The SKIP flag can also be used for
1060'commenting out' broken examples.
1061
1062 >>> import unavailable_resource # doctest: +SKIP
1063 >>> unavailable_resource.do_something() # doctest: +SKIP
1064 >>> unavailable_resource.blow_up() # doctest: +SKIP
1065 Traceback (most recent call last):
1066 ...
1067 UncheckedBlowUpError: Nobody checks me.
1068
1069 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001070 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001071 0.721216923889
1072
Edward Loper71f55af2004-08-26 01:41:51 +00001073The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001074and actual outputs to be displayed using a unified diff:
1075
1076 >>> def f(x):
1077 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001078 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001079 ... a
1080 ... B
1081 ... c
1082 ... d
1083 ... f
1084 ... g
1085 ... h
1086 ... '''
1087
1088 >>> # Without the flag:
1089 >>> test = doctest.DocTestFinder().find(f)[0]
1090 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001091 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001092 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001093 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001094 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001095 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001096 Expected:
1097 a
1098 B
1099 c
1100 d
1101 f
1102 g
1103 h
1104 Got:
1105 a
1106 b
1107 c
1108 d
1109 e
1110 f
1111 g
1112 (1, 1)
1113
1114 >>> # With the flag:
1115 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001116 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001117 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).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 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001121 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001122 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001123 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001124 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001125 a
1126 -B
1127 +b
1128 c
1129 d
1130 +e
1131 f
1132 g
1133 -h
Tim Peters8485b562004-08-04 18:46:34 +00001134 (1, 1)
1135
Edward Loper71f55af2004-08-26 01:41:51 +00001136The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001137and actual outputs to be displayed using a context diff:
1138
Edward Loper71f55af2004-08-26 01:41:51 +00001139 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001140 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001141 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001142 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001143 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001144 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001145 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001146 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001147 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001148 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001149 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001150 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001151 a
1152 ! B
1153 c
1154 d
1155 f
1156 g
1157 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001158 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001159 a
1160 ! b
1161 c
1162 d
1163 + e
1164 f
1165 g
Tim Peters8485b562004-08-04 18:46:34 +00001166 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001167
1168
Edward Loper71f55af2004-08-26 01:41:51 +00001169The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001170used by the popular ndiff.py utility. This does intraline difference
1171marking, as well as interline differences.
1172
1173 >>> def f(x):
1174 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001175 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001176 ... a b c d e f g h i j k 1 m
1177 ... '''
1178 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001179 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001180 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001181 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001182 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001183 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001184 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001185 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001186 Differences (ndiff with -expected +actual):
1187 - a b c d e f g h i j k 1 m
1188 ? ^
1189 + a b c d e f g h i j k l m
1190 ? + ++ ^
Tim Petersc6cbab02004-08-22 19:43:28 +00001191 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001192
1193The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1194failing example:
1195
1196 >>> def f(x):
1197 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001198 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001199 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001200 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001201 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001202 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001203 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001204 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001205 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001206 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001207 ... 500
1208 ... '''
1209 >>> test = doctest.DocTestFinder().find(f)[0]
1210 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1211 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001212 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001213 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001214 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001215 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001216 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001217 Expected:
1218 200
1219 Got:
1220 2
1221 (3, 5)
1222
1223However, output from `report_start` is not supressed:
1224
1225 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001226 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001227 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001228 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001229 Expecting:
1230 1
1231 ok
1232 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001233 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001234 Expecting:
1235 200
1236 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001237 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001238 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001239 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001240 Expected:
1241 200
1242 Got:
1243 2
1244 (3, 5)
1245
1246For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1247count as failures:
1248
1249 >>> def f(x):
1250 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001251 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001252 ... 1
1253 ... >>> raise ValueError(2) # first failure
1254 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001255 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001256 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001257 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001258 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001259 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001260 ... 500
1261 ... '''
1262 >>> test = doctest.DocTestFinder().find(f)[0]
1263 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1264 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1265 ... # doctest: +ELLIPSIS
1266 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001267 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001268 Failed example:
1269 raise ValueError(2) # first failure
1270 Exception raised:
1271 ...
1272 ValueError: 2
1273 (3, 5)
1274
Thomas Wouters477c8d52006-05-27 19:21:47 +00001275New option flags can also be registered, via register_optionflag(). Here
1276we reach into doctest's internals a bit.
1277
1278 >>> unlikely = "UNLIKELY_OPTION_NAME"
1279 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1280 False
1281 >>> new_flag_value = doctest.register_optionflag(unlikely)
1282 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1283 True
1284
1285Before 2.4.4/2.5, registering a name more than once erroneously created
1286more than one flag value. Here we verify that's fixed:
1287
1288 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1289 >>> redundant_flag_value == new_flag_value
1290 True
1291
1292Clean up.
1293 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1294
Tim Petersc6cbab02004-08-22 19:43:28 +00001295 """
1296
Tim Peters8485b562004-08-04 18:46:34 +00001297 def option_directives(): r"""
1298Tests of `DocTestRunner`'s option directive mechanism.
1299
Edward Loper74bca7a2004-08-12 02:27:44 +00001300Option directives can be used to turn option flags on or off for a
1301single example. To turn an option on for an example, follow that
1302example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001303
1304 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001305 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001306 ... [0, 1, ..., 9]
1307 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001308 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001309 ... [0, 1, ..., 9]
1310 ... '''
1311 >>> test = doctest.DocTestFinder().find(f)[0]
1312 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001313 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001314 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001315 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001316 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001317 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001318 Expected:
1319 [0, 1, ..., 9]
1320 Got:
1321 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001322 (1, 2)
1323
1324To turn an option off for an example, follow that example with a
1325comment of the form ``# doctest: -OPTION``:
1326
1327 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001328 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001329 ... [0, 1, ..., 9]
1330 ...
1331 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001332 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001333 ... [0, 1, ..., 9]
1334 ... '''
1335 >>> test = doctest.DocTestFinder().find(f)[0]
1336 >>> doctest.DocTestRunner(verbose=False,
1337 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001338 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001339 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001340 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001341 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001342 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001343 Expected:
1344 [0, 1, ..., 9]
1345 Got:
1346 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001347 (1, 2)
1348
1349Option directives affect only the example that they appear with; they
1350do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001351
Edward Loper74bca7a2004-08-12 02:27:44 +00001352 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001353 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001354 ... [0, 1, ..., 9]
1355 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001356 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001357 ... [0, 1, ..., 9]
1358 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001359 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001360 ... [0, 1, ..., 9]
1361 ... '''
1362 >>> test = doctest.DocTestFinder().find(f)[0]
1363 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001364 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001365 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001366 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001367 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001368 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001369 Expected:
1370 [0, 1, ..., 9]
1371 Got:
1372 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001373 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001374 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001375 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001376 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001377 Expected:
1378 [0, 1, ..., 9]
1379 Got:
1380 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001381 (2, 3)
1382
Edward Loper74bca7a2004-08-12 02:27:44 +00001383Multiple options may be modified by a single option directive. They
1384may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001385
1386 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001387 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001388 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001389 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001390 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001391 ... [0, 1, ..., 9]
1392 ... '''
1393 >>> test = doctest.DocTestFinder().find(f)[0]
1394 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001395 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001396 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001397 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001398 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001399 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001400 Expected:
1401 [0, 1, ..., 9]
1402 Got:
1403 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001404 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001405
1406 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001407 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001408 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001409 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001410 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
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:
Guido van Rossum805365e2007-05-07 22:24:25 +00001419 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001420 Expected:
1421 [0, 1, ..., 9]
1422 Got:
1423 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001424 (1, 2)
1425
1426 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001427 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001428 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001429 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001430 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1431 ... [0, 1, ..., 9]
1432 ... '''
1433 >>> test = doctest.DocTestFinder().find(f)[0]
1434 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001435 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001436 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001437 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001438 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001439 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001440 Expected:
1441 [0, 1, ..., 9]
1442 Got:
1443 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001444 (1, 2)
1445
1446The option directive may be put on the line following the source, as
1447long as a continuation prompt is used:
1448
1449 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001450 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001451 ... ... # doctest: +ELLIPSIS
1452 ... [0, 1, ..., 9]
1453 ... '''
1454 >>> test = doctest.DocTestFinder().find(f)[0]
1455 >>> doctest.DocTestRunner(verbose=False).run(test)
1456 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001457
Edward Loper74bca7a2004-08-12 02:27:44 +00001458For examples with multi-line source, the option directive may appear
1459at the end of any line:
1460
1461 >>> def f(x): r'''
1462 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001463 ... ... print(' ', x, end='', sep='')
1464 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001465 ...
1466 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001467 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1468 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001469 ... '''
1470 >>> test = doctest.DocTestFinder().find(f)[0]
1471 >>> doctest.DocTestRunner(verbose=False).run(test)
1472 (0, 2)
1473
1474If more than one line of an example with multi-line source has an
1475option directive, then they are combined:
1476
1477 >>> def f(x): r'''
1478 ... Should fail (option directive not on the last line):
1479 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001480 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001481 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001482 ... '''
1483 >>> test = doctest.DocTestFinder().find(f)[0]
1484 >>> doctest.DocTestRunner(verbose=False).run(test)
1485 (0, 1)
1486
1487It is an error to have a comment of the form ``# doctest:`` that is
1488*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1489``OPTION`` is an option that has been registered with
1490`register_option`:
1491
1492 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001493 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001494 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1495 Traceback (most recent call last):
1496 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1497
1498 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001499 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001500 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1501 Traceback (most recent call last):
1502 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1503
1504It is an error to use an option directive on a line that contains no
1505source:
1506
1507 >>> s = '>>> # doctest: +ELLIPSIS'
1508 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1509 Traceback (most recent call last):
1510 ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
Tim Peters8485b562004-08-04 18:46:34 +00001511"""
1512
1513def test_testsource(): r"""
1514Unit tests for `testsource()`.
1515
1516The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001517test with that name in that module, and converts it to a script. The
1518example code is converted to regular Python code. The surrounding
1519words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001520
1521 >>> import test.test_doctest
1522 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001523 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001524 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001525 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001526 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001527 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001528 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001529 #
Edward Lopera5db6002004-08-12 02:41:30 +00001530 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001531 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001532
1533 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001534 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001535 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001536 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001537 ## 1
1538 ## 2
1539 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001540 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001541
1542 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001543 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001544 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001545 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001546 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001547 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001548 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001549 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001550 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001551"""
1552
1553def test_debug(): r"""
1554
1555Create a docstring that we want to debug:
1556
1557 >>> s = '''
1558 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001559 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001560 ... 12
1561 ... '''
1562
1563Create some fake stdin input, to feed to the debugger:
1564
1565 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001566 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001567 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001568
1569Run the debugger on the docstring, and then restore sys.stdin.
1570
Edward Loper2de91ba2004-08-27 02:07:46 +00001571 >>> try: doctest.debug_src(s)
1572 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001573 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001574 (Pdb) next
1575 12
Tim Peters8485b562004-08-04 18:46:34 +00001576 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001577 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001578 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001579 12
1580 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001581
1582"""
1583
Jim Fulton356fd192004-08-09 11:34:47 +00001584def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001585 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001586
Tim Peters413ced62004-08-09 15:43:47 +00001587 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001588 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001589 you use it. The doctest module changes sys.stdout so that it can
1590 capture program output. It also temporarily replaces pdb.set_trace
1591 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001592 see debugger output.
1593
1594 >>> doc = '''
1595 ... >>> x = 42
1596 ... >>> import pdb; pdb.set_trace()
1597 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001598 >>> parser = doctest.DocTestParser()
1599 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001600 >>> runner = doctest.DocTestRunner(verbose=False)
1601
1602 To demonstrate this, we'll create a fake standard input that
1603 captures our debugger input:
1604
1605 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001606 >>> real_stdin = sys.stdin
1607 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001608 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001609 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001610 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001611
Edward Loper2de91ba2004-08-27 02:07:46 +00001612 >>> try: runner.run(test)
1613 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001614 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001615 > <doctest foo[1]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001616 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001617 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001618 42
1619 (Pdb) continue
1620 (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001621
1622 You can also put pdb.set_trace in a function called from a test:
1623
1624 >>> def calls_set_trace():
1625 ... y=2
1626 ... import pdb; pdb.set_trace()
1627
1628 >>> doc = '''
1629 ... >>> x=1
1630 ... >>> calls_set_trace()
1631 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001632 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001633 >>> real_stdin = sys.stdin
1634 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001635 ... 'print(y)', # print data defined in the function
Jim Fulton356fd192004-08-09 11:34:47 +00001636 ... 'up', # out of function
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001637 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001638 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001639 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001640
Tim Peters50c6bdb2004-11-08 22:07:37 +00001641 >>> try:
1642 ... runner.run(test)
1643 ... finally:
1644 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001645 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001646 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1647 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001648 (Pdb) print(y)
Edward Loper2de91ba2004-08-27 02:07:46 +00001649 2
1650 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001651 > <doctest foo[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001652 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001653 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001654 1
1655 (Pdb) continue
1656 (0, 2)
1657
1658 During interactive debugging, source code is shown, even for
1659 doctest examples:
1660
1661 >>> doc = '''
1662 ... >>> def f(x):
1663 ... ... g(x*2)
1664 ... >>> def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001665 ... ... print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001666 ... ... import pdb; pdb.set_trace()
1667 ... >>> f(3)
1668 ... '''
1669 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1670 >>> real_stdin = sys.stdin
1671 >>> sys.stdin = _FakeInput([
1672 ... 'list', # list source from example 2
1673 ... 'next', # return from g()
1674 ... 'list', # list source from example 1
1675 ... 'next', # return from f()
1676 ... 'list', # list source from example 3
1677 ... 'continue', # stop debugging
1678 ... ''])
1679 >>> try: runner.run(test)
1680 ... finally: sys.stdin = real_stdin
1681 ... # doctest: +NORMALIZE_WHITESPACE
1682 --Return--
1683 > <doctest foo[1]>(3)g()->None
1684 -> import pdb; pdb.set_trace()
1685 (Pdb) list
1686 1 def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001687 2 print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001688 3 -> import pdb; pdb.set_trace()
1689 [EOF]
1690 (Pdb) next
1691 --Return--
1692 > <doctest foo[0]>(2)f()->None
1693 -> g(x*2)
1694 (Pdb) list
1695 1 def f(x):
1696 2 -> g(x*2)
1697 [EOF]
1698 (Pdb) next
1699 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700 > <doctest foo[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001701 -> f(3)
1702 (Pdb) list
1703 1 -> f(3)
1704 [EOF]
1705 (Pdb) continue
1706 **********************************************************************
1707 File "foo.py", line 7, in foo
1708 Failed example:
1709 f(3)
1710 Expected nothing
1711 Got:
1712 9
1713 (1, 3)
Jim Fulton356fd192004-08-09 11:34:47 +00001714 """
1715
Tim Peters50c6bdb2004-11-08 22:07:37 +00001716def test_pdb_set_trace_nested():
1717 """This illustrates more-demanding use of set_trace with nested functions.
1718
1719 >>> class C(object):
1720 ... def calls_set_trace(self):
1721 ... y = 1
1722 ... import pdb; pdb.set_trace()
1723 ... self.f1()
1724 ... y = 2
1725 ... def f1(self):
1726 ... x = 1
1727 ... self.f2()
1728 ... x = 2
1729 ... def f2(self):
1730 ... z = 1
1731 ... z = 2
1732
1733 >>> calls_set_trace = C().calls_set_trace
1734
1735 >>> doc = '''
1736 ... >>> a = 1
1737 ... >>> calls_set_trace()
1738 ... '''
1739 >>> parser = doctest.DocTestParser()
1740 >>> runner = doctest.DocTestRunner(verbose=False)
1741 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1742 >>> real_stdin = sys.stdin
1743 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001744 ... 'print(y)', # print data defined in the function
1745 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1746 ... 'up', 'print(x)',
1747 ... 'up', 'print(y)',
1748 ... 'up', 'print(foo)',
Tim Peters50c6bdb2004-11-08 22:07:37 +00001749 ... 'continue', # stop debugging
1750 ... ''])
1751
1752 >>> try:
1753 ... runner.run(test)
1754 ... finally:
1755 ... sys.stdin = real_stdin
1756 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1757 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001758 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001759 1
1760 (Pdb) step
1761 --Call--
1762 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1763 -> def f1(self):
1764 (Pdb) step
1765 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1766 -> x = 1
1767 (Pdb) step
1768 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1769 -> self.f2()
1770 (Pdb) step
1771 --Call--
1772 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1773 -> def f2(self):
1774 (Pdb) step
1775 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1776 -> z = 1
1777 (Pdb) step
1778 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1779 -> z = 2
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001780 (Pdb) print(z)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001781 1
1782 (Pdb) up
1783 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1784 -> self.f2()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001785 (Pdb) print(x)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001786 1
1787 (Pdb) up
1788 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1789 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001790 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001791 1
1792 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793 > <doctest foo[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001794 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001795 (Pdb) print(foo)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001796 *** NameError: name 'foo' is not defined
1797 (Pdb) continue
1798 (0, 2)
1799"""
1800
Tim Peters19397e52004-08-06 22:02:59 +00001801def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001802 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001803
1804 We create a Suite by providing a module. A module can be provided
1805 by passing a module object:
1806
1807 >>> import unittest
1808 >>> import test.sample_doctest
1809 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1810 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001811 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001812
1813 We can also supply the module by name:
1814
1815 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1816 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001817 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001818
1819 We can use the current module:
1820
1821 >>> suite = test.sample_doctest.test_suite()
1822 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001823 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001824
1825 We can supply global variables. If we pass globs, they will be
1826 used instead of the module globals. Here we'll pass an empty
1827 globals, triggering an extra error:
1828
1829 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1830 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001831 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001832
1833 Alternatively, we can provide extra globals. Here we'll make an
1834 error go away by providing an extra global variable:
1835
1836 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1837 ... extraglobs={'y': 1})
1838 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001839 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001840
1841 You can pass option flags. Here we'll cause an extra error
1842 by disabling the blank-line feature:
1843
1844 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001845 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001846 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001847 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001848
Tim Peters1e277ee2004-08-07 05:37:52 +00001849 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001850
Jim Fultonf54bad42004-08-28 14:57:56 +00001851 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001852 ... import test.test_doctest
1853 ... test.test_doctest.sillySetup = True
1854
Jim Fultonf54bad42004-08-28 14:57:56 +00001855 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001856 ... import test.test_doctest
1857 ... del test.test_doctest.sillySetup
1858
1859 Here, we installed a silly variable that the test expects:
1860
1861 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1862 ... setUp=setUp, tearDown=tearDown)
1863 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001864 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001865
1866 But the tearDown restores sanity:
1867
1868 >>> import test.test_doctest
1869 >>> test.test_doctest.sillySetup
1870 Traceback (most recent call last):
1871 ...
1872 AttributeError: 'module' object has no attribute 'sillySetup'
1873
Jim Fultonf54bad42004-08-28 14:57:56 +00001874 The setUp and tearDown funtions are passed test objects. Here
1875 we'll use the setUp function to supply the missing variable y:
1876
1877 >>> def setUp(test):
1878 ... test.globs['y'] = 1
1879
1880 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1881 >>> suite.run(unittest.TestResult())
1882 <unittest.TestResult run=9 errors=0 failures=3>
1883
1884 Here, we didn't need to use a tearDown function because we
1885 modified the test globals, which are a copy of the
1886 sample_doctest module dictionary. The test globals are
1887 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001888 """
1889
1890def test_DocFileSuite():
1891 """We can test tests found in text files using a DocFileSuite.
1892
1893 We create a suite by providing the names of one or more text
1894 files that include examples:
1895
1896 >>> import unittest
1897 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001898 ... 'test_doctest2.txt',
1899 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00001900 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00001901 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001902
1903 The test files are looked for in the directory containing the
1904 calling module. A package keyword argument can be provided to
1905 specify a different relative location.
1906
1907 >>> import unittest
1908 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1909 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001910 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001911 ... package='test')
1912 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00001913 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001914
Edward Loper0273f5b2004-09-18 20:27:04 +00001915 '/' should be used as a path separator. It will be converted
1916 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001917
1918 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1919 >>> suite.run(unittest.TestResult())
1920 <unittest.TestResult run=1 errors=0 failures=1>
1921
Edward Loper0273f5b2004-09-18 20:27:04 +00001922 If DocFileSuite is used from an interactive session, then files
1923 are resolved relative to the directory of sys.argv[0]:
1924
1925 >>> import new, os.path, test.test_doctest
1926 >>> save_argv = sys.argv
1927 >>> sys.argv = [test.test_doctest.__file__]
1928 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1929 ... package=new.module('__main__'))
1930 >>> sys.argv = save_argv
1931
Edward Loper052d0cd2004-09-19 17:19:33 +00001932 By setting `module_relative=False`, os-specific paths may be
1933 used (including absolute paths and paths relative to the
1934 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00001935
1936 >>> # Get the absolute path of the test package.
1937 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
1938 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
1939
1940 >>> # Use it to find the absolute path of test_doctest.txt.
1941 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
1942
Edward Loper052d0cd2004-09-19 17:19:33 +00001943 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00001944 >>> suite.run(unittest.TestResult())
1945 <unittest.TestResult run=1 errors=0 failures=1>
1946
Edward Loper052d0cd2004-09-19 17:19:33 +00001947 It is an error to specify `package` when `module_relative=False`:
1948
1949 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
1950 ... package='test')
1951 Traceback (most recent call last):
1952 ValueError: Package may only be specified for module-relative paths.
1953
Tim Peters19397e52004-08-06 22:02:59 +00001954 You can specify initial global variables:
1955
1956 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1957 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001958 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001959 ... globs={'favorite_color': 'blue'})
1960 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00001961 <unittest.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001962
1963 In this case, we supplied a missing favorite color. You can
1964 provide doctest options:
1965
1966 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1967 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001968 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001969 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1970 ... globs={'favorite_color': 'blue'})
1971 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00001972 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001973
1974 And, you can provide setUp and tearDown functions:
1975
1976 You can supply setUp and teatDoen functions:
1977
Jim Fultonf54bad42004-08-28 14:57:56 +00001978 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001979 ... import test.test_doctest
1980 ... test.test_doctest.sillySetup = True
1981
Jim Fultonf54bad42004-08-28 14:57:56 +00001982 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001983 ... import test.test_doctest
1984 ... del test.test_doctest.sillySetup
1985
1986 Here, we installed a silly variable that the test expects:
1987
1988 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1989 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001990 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001991 ... setUp=setUp, tearDown=tearDown)
1992 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00001993 <unittest.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001994
1995 But the tearDown restores sanity:
1996
1997 >>> import test.test_doctest
1998 >>> test.test_doctest.sillySetup
1999 Traceback (most recent call last):
2000 ...
2001 AttributeError: 'module' object has no attribute 'sillySetup'
2002
Jim Fultonf54bad42004-08-28 14:57:56 +00002003 The setUp and tearDown funtions are passed test objects.
2004 Here, we'll use a setUp function to set the favorite color in
2005 test_doctest.txt:
2006
2007 >>> def setUp(test):
2008 ... test.globs['favorite_color'] = 'blue'
2009
2010 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2011 >>> suite.run(unittest.TestResult())
2012 <unittest.TestResult run=1 errors=0 failures=0>
2013
2014 Here, we didn't need to use a tearDown function because we
2015 modified the test globals. The test globals are
2016 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002017
Fred Drake7c404a42004-12-21 23:46:34 +00002018 Tests in a file run using `DocFileSuite` can also access the
2019 `__file__` global, which is set to the name of the file
2020 containing the tests:
2021
2022 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2023 >>> suite.run(unittest.TestResult())
2024 <unittest.TestResult run=1 errors=0 failures=0>
2025
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002026 If the tests contain non-ASCII characters, we have to specify which
2027 encoding the file is encoded with. We do so by using the `encoding`
2028 parameter:
2029
2030 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2031 ... 'test_doctest2.txt',
2032 ... 'test_doctest4.txt',
2033 ... encoding='utf-8')
2034 >>> suite.run(unittest.TestResult())
2035 <unittest.TestResult run=3 errors=0 failures=2>
2036
Jim Fultonf54bad42004-08-28 14:57:56 +00002037 """
Tim Peters19397e52004-08-06 22:02:59 +00002038
Jim Fulton07a349c2004-08-22 14:10:00 +00002039def test_trailing_space_in_test():
2040 """
Tim Petersa7def722004-08-23 22:13:22 +00002041 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002042
Jim Fulton07a349c2004-08-22 14:10:00 +00002043 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002044 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002045 foo \n
2046 """
Tim Peters19397e52004-08-06 22:02:59 +00002047
Jim Fultonf54bad42004-08-28 14:57:56 +00002048
2049def test_unittest_reportflags():
2050 """Default unittest reporting flags can be set to control reporting
2051
2052 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2053 only the first failure of each test. First, we'll look at the
2054 output without the flag. The file test_doctest.txt file has two
2055 tests. They both fail if blank lines are disabled:
2056
2057 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2058 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2059 >>> import unittest
2060 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002061 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002062 Traceback ...
2063 Failed example:
2064 favorite_color
2065 ...
2066 Failed example:
2067 if 1:
2068 ...
2069
2070 Note that we see both failures displayed.
2071
2072 >>> old = doctest.set_unittest_reportflags(
2073 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2074
2075 Now, when we run the test:
2076
2077 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002078 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002079 Traceback ...
2080 Failed example:
2081 favorite_color
2082 Exception raised:
2083 ...
2084 NameError: name 'favorite_color' is not defined
2085 <BLANKLINE>
2086 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002087
Jim Fultonf54bad42004-08-28 14:57:56 +00002088 We get only the first failure.
2089
2090 If we give any reporting options when we set up the tests,
2091 however:
2092
2093 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2094 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2095
2096 Then the default eporting options are ignored:
2097
2098 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002099 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002100 Traceback ...
2101 Failed example:
2102 favorite_color
2103 ...
2104 Failed example:
2105 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002106 print('a')
2107 print()
2108 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002109 Differences (ndiff with -expected +actual):
2110 a
2111 - <BLANKLINE>
2112 +
2113 b
2114 <BLANKLINE>
2115 <BLANKLINE>
2116
2117
2118 Test runners can restore the formatting flags after they run:
2119
2120 >>> ignored = doctest.set_unittest_reportflags(old)
2121
2122 """
2123
Edward Loper052d0cd2004-09-19 17:19:33 +00002124def test_testfile(): r"""
2125Tests for the `testfile()` function. This function runs all the
2126doctest examples in a given file. In its simple invokation, it is
2127called with the name of a file, which is taken to be relative to the
2128calling module. The return value is (#failures, #tests).
2129
2130 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2131 **********************************************************************
2132 File "...", line 6, in test_doctest.txt
2133 Failed example:
2134 favorite_color
2135 Exception raised:
2136 ...
2137 NameError: name 'favorite_color' is not defined
2138 **********************************************************************
2139 1 items had failures:
2140 1 of 2 in test_doctest.txt
2141 ***Test Failed*** 1 failures.
2142 (1, 2)
2143 >>> doctest.master = None # Reset master.
2144
2145(Note: we'll be clearing doctest.master after each call to
2146`doctest.testfile`, to supress warnings about multiple tests with the
2147same name.)
2148
2149Globals may be specified with the `globs` and `extraglobs` parameters:
2150
2151 >>> globs = {'favorite_color': 'blue'}
2152 >>> doctest.testfile('test_doctest.txt', globs=globs)
2153 (0, 2)
2154 >>> doctest.master = None # Reset master.
2155
2156 >>> extraglobs = {'favorite_color': 'red'}
2157 >>> doctest.testfile('test_doctest.txt', globs=globs,
2158 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2159 **********************************************************************
2160 File "...", line 6, in test_doctest.txt
2161 Failed example:
2162 favorite_color
2163 Expected:
2164 'blue'
2165 Got:
2166 'red'
2167 **********************************************************************
2168 1 items had failures:
2169 1 of 2 in test_doctest.txt
2170 ***Test Failed*** 1 failures.
2171 (1, 2)
2172 >>> doctest.master = None # Reset master.
2173
2174The file may be made relative to a given module or package, using the
2175optional `module_relative` parameter:
2176
2177 >>> doctest.testfile('test_doctest.txt', globs=globs,
2178 ... module_relative='test')
2179 (0, 2)
2180 >>> doctest.master = None # Reset master.
2181
2182Verbosity can be increased with the optional `verbose` paremter:
2183
2184 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2185 Trying:
2186 favorite_color
2187 Expecting:
2188 'blue'
2189 ok
2190 Trying:
2191 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002192 print('a')
2193 print()
2194 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002195 Expecting:
2196 a
2197 <BLANKLINE>
2198 b
2199 ok
2200 1 items passed all tests:
2201 2 tests in test_doctest.txt
2202 2 tests in 1 items.
2203 2 passed and 0 failed.
2204 Test passed.
2205 (0, 2)
2206 >>> doctest.master = None # Reset master.
2207
2208The name of the test may be specified with the optional `name`
2209parameter:
2210
2211 >>> doctest.testfile('test_doctest.txt', name='newname')
2212 ... # doctest: +ELLIPSIS
2213 **********************************************************************
2214 File "...", line 6, in newname
2215 ...
2216 (1, 2)
2217 >>> doctest.master = None # Reset master.
2218
2219The summary report may be supressed with the optional `report`
2220parameter:
2221
2222 >>> doctest.testfile('test_doctest.txt', report=False)
2223 ... # doctest: +ELLIPSIS
2224 **********************************************************************
2225 File "...", line 6, in test_doctest.txt
2226 Failed example:
2227 favorite_color
2228 Exception raised:
2229 ...
2230 NameError: name 'favorite_color' is not defined
2231 (1, 2)
2232 >>> doctest.master = None # Reset master.
2233
2234The optional keyword argument `raise_on_error` can be used to raise an
2235exception on the first error (which may be useful for postmortem
2236debugging):
2237
2238 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2239 ... # doctest: +ELLIPSIS
2240 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002241 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002242 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002243
2244If the tests contain non-ASCII characters, the tests might fail, since
2245it's unknown which encoding is used. The encoding can be specified
2246using the optional keyword argument `encoding`:
2247
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002248 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002249 **********************************************************************
2250 File "...", line 7, in test_doctest4.txt
2251 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002252 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002253 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002254 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002255 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002256 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002257 **********************************************************************
2258 ...
2259 **********************************************************************
2260 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002261 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002262 ***Test Failed*** 2 failures.
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002263 (2, 2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002264 >>> doctest.master = None # Reset master.
2265
2266 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002267 (0, 2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002268 >>> doctest.master = None # Reset master.
Edward Loper052d0cd2004-09-19 17:19:33 +00002269"""
2270
Tim Petersa7def722004-08-23 22:13:22 +00002271# old_test1, ... used to live in doctest.py, but cluttered it. Note
2272# that these use the deprecated doctest.Tester, so should go away (or
2273# be rewritten) someday.
2274
2275# Ignore all warnings about the use of class Tester in this module.
2276# Note that the name of this module may differ depending on how it's
2277# imported, so the use of __name__ is important.
2278warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2279 __name__, 0)
2280
2281def old_test1(): r"""
2282>>> from doctest import Tester
2283>>> t = Tester(globs={'x': 42}, verbose=0)
2284>>> t.runstring(r'''
2285... >>> x = x * 2
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002286... >>> print(x)
Tim Petersa7def722004-08-23 22:13:22 +00002287... 42
2288... ''', 'XYZ')
2289**********************************************************************
2290Line 3, in XYZ
2291Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002292 print(x)
Tim Petersa7def722004-08-23 22:13:22 +00002293Expected:
2294 42
2295Got:
2296 84
2297(1, 2)
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002298>>> t.runstring(">>> x = x * 2\n>>> print(x)\n84\n", 'example2')
Tim Petersa7def722004-08-23 22:13:22 +00002299(0, 2)
2300>>> t.summarize()
2301**********************************************************************
23021 items had failures:
2303 1 of 2 in XYZ
2304***Test Failed*** 1 failures.
2305(1, 4)
2306>>> t.summarize(verbose=1)
23071 items passed all tests:
2308 2 tests in example2
2309**********************************************************************
23101 items had failures:
2311 1 of 2 in XYZ
23124 tests in 2 items.
23133 passed and 1 failed.
2314***Test Failed*** 1 failures.
2315(1, 4)
2316"""
2317
2318def old_test2(): r"""
2319 >>> from doctest import Tester
2320 >>> t = Tester(globs={}, verbose=1)
2321 >>> test = r'''
2322 ... # just an example
2323 ... >>> x = 1 + 2
2324 ... >>> x
2325 ... 3
2326 ... '''
2327 >>> t.runstring(test, "Example")
2328 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002329 Trying:
2330 x = 1 + 2
2331 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002332 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002333 Trying:
2334 x
2335 Expecting:
2336 3
Tim Petersa7def722004-08-23 22:13:22 +00002337 ok
2338 0 of 2 examples failed in string Example
2339 (0, 2)
2340"""
2341
2342def old_test3(): r"""
2343 >>> from doctest import Tester
2344 >>> t = Tester(globs={}, verbose=0)
2345 >>> def _f():
2346 ... '''Trivial docstring example.
2347 ... >>> assert 2 == 2
2348 ... '''
2349 ... return 32
2350 ...
2351 >>> t.rundoc(_f) # expect 0 failures in 1 example
2352 (0, 1)
2353"""
2354
2355def old_test4(): """
2356 >>> import new
2357 >>> m1 = new.module('_m1')
2358 >>> m2 = new.module('_m2')
2359 >>> test_data = \"""
2360 ... def _f():
2361 ... '''>>> assert 1 == 1
2362 ... '''
2363 ... def g():
2364 ... '''>>> assert 2 != 1
2365 ... '''
2366 ... class H:
2367 ... '''>>> assert 2 > 1
2368 ... '''
2369 ... def bar(self):
2370 ... '''>>> assert 1 < 2
2371 ... '''
2372 ... \"""
Georg Brandl7cae87c2006-09-06 06:51:57 +00002373 >>> exec(test_data, m1.__dict__)
2374 >>> exec(test_data, m2.__dict__)
Tim Petersa7def722004-08-23 22:13:22 +00002375 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2376
2377 Tests that objects outside m1 are excluded:
2378
2379 >>> from doctest import Tester
2380 >>> t = Tester(globs={}, verbose=0)
2381 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
2382 (0, 4)
2383
2384 Once more, not excluding stuff outside m1:
2385
2386 >>> t = Tester(globs={}, verbose=0)
2387 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2388 (0, 8)
2389
2390 The exclusion of objects from outside the designated module is
2391 meant to be invoked automagically by testmod.
2392
2393 >>> doctest.testmod(m1, verbose=False)
2394 (0, 4)
2395"""
2396
Tim Peters8485b562004-08-04 18:46:34 +00002397######################################################################
2398## Main
2399######################################################################
2400
2401def test_main():
2402 # Check the doctest cases in doctest itself:
2403 test_support.run_doctest(doctest, verbosity=True)
2404 # Check the doctest cases defined here:
2405 from test import test_doctest
2406 test_support.run_doctest(test_doctest, verbosity=True)
2407
2408import trace, sys, re, StringIO
2409def test_coverage(coverdir):
2410 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2411 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002412 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002413 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002414 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002415 r.write_results(show_missing=True, summary=True,
2416 coverdir=coverdir)
2417
2418if __name__ == '__main__':
2419 if '-c' in sys.argv:
2420 test_coverage('/tmp/doctest.cover')
2421 else:
2422 test_main()