blob: 33163b938791bc7bc1ddc435946a181f426695c2 [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Yury Selivanovb532df62014-12-08 15:00:05 -05007import functools
Victor Stinner9d396392010-10-16 21:54:59 +00008import os
Brett Cannon31f59292011-02-21 19:29:56 +00009import sys
Tim Peters8485b562004-08-04 18:46:34 +000010
Florent Xiclunadc6f2d02010-04-02 19:25:32 +000011
Nick Coghlanf088e5e2008-12-14 11:50:48 +000012# NOTE: There are some additional tests relating to interaction with
13# zipimport in the test_zipimport_support test module.
14
Tim Peters8485b562004-08-04 18:46:34 +000015######################################################################
16## Sample Objects (used by test cases)
17######################################################################
18
19def sample_func(v):
20 """
Tim Peters19397e52004-08-06 22:02:59 +000021 Blah blah
22
Guido van Rossum7131f842007-02-09 20:13:25 +000023 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000024 44
Tim Peters19397e52004-08-06 22:02:59 +000025
26 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000027 """
28 return v+v
29
30class SampleClass:
31 """
Guido van Rossum7131f842007-02-09 20:13:25 +000032 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000033 1
Edward Loper4ae900f2004-09-21 03:20:34 +000034
35 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
36 >>>
37 ...
38
39 Multiline example:
40 >>> sc = SampleClass(3)
41 >>> for i in range(10):
42 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000043 ... print(' ', sc.get(), sep='', end='')
44 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000045 """
46 def __init__(self, val):
47 """
Guido van Rossum7131f842007-02-09 20:13:25 +000048 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000049 12
50 """
51 self.val = val
52
53 def double(self):
54 """
Guido van Rossum7131f842007-02-09 20:13:25 +000055 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000056 24
57 """
58 return SampleClass(self.val + self.val)
59
60 def get(self):
61 """
Guido van Rossum7131f842007-02-09 20:13:25 +000062 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000063 -5
64 """
65 return self.val
66
67 def a_staticmethod(v):
68 """
Guido van Rossum7131f842007-02-09 20:13:25 +000069 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000070 11
71 """
72 return v+1
73 a_staticmethod = staticmethod(a_staticmethod)
74
75 def a_classmethod(cls, v):
76 """
Guido van Rossum7131f842007-02-09 20:13:25 +000077 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000078 12
Guido van Rossum7131f842007-02-09 20:13:25 +000079 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000080 12
81 """
82 return v+2
83 a_classmethod = classmethod(a_classmethod)
84
85 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000086 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000087 22
88 """)
89
90 class NestedClass:
91 """
92 >>> x = SampleClass.NestedClass(5)
93 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000094 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000095 25
96 """
97 def __init__(self, val=0):
98 """
Guido van Rossum7131f842007-02-09 20:13:25 +000099 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +0000100 0
101 """
102 self.val = val
103 def square(self):
104 return SampleClass.NestedClass(self.val*self.val)
105 def get(self):
106 return self.val
107
108class SampleNewStyleClass(object):
109 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000110 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000111 1
112 2
113 3
114 """
115 def __init__(self, val):
116 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000117 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000118 12
119 """
120 self.val = val
121
122 def double(self):
123 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000124 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000125 24
126 """
127 return SampleNewStyleClass(self.val + self.val)
128
129 def get(self):
130 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000131 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000132 -5
133 """
134 return self.val
135
136######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000137## Fake stdin (for testing interactive debugging)
138######################################################################
139
140class _FakeInput:
141 """
142 A fake input stream for pdb's interactive debugger. Whenever a
143 line is read, print it (to simulate the user typing it), and then
144 return it. The set of lines to return is specified in the
145 constructor; they should not have trailing newlines.
146 """
147 def __init__(self, lines):
148 self.lines = lines
149
150 def readline(self):
151 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000152 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000153 return line+'\n'
154
155######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000156## Test Cases
157######################################################################
158
159def test_Example(): r"""
160Unit tests for the `Example` class.
161
Edward Lopera6b68322004-08-26 00:05:43 +0000162Example is a simple container class that holds:
163 - `source`: A source string.
164 - `want`: An expected output string.
165 - `exc_msg`: An expected exception message string (or None if no
166 exception is expected).
167 - `lineno`: A line number (within the docstring).
168 - `indent`: The example's indentation in the input string.
169 - `options`: An option dictionary, mapping option flags to True or
170 False.
Tim Peters8485b562004-08-04 18:46:34 +0000171
Edward Lopera6b68322004-08-26 00:05:43 +0000172These attributes are set by the constructor. `source` and `want` are
173required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000174
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000175 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000176 >>> (example.source, example.want, example.exc_msg,
177 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000178 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000179
180The first three attributes (`source`, `want`, and `exc_msg`) may be
181specified positionally; the remaining arguments should be specified as
182keyword arguments:
183
184 >>> exc_msg = 'IndexError: pop from an empty list'
185 >>> example = doctest.Example('[].pop()', '', exc_msg,
186 ... lineno=5, indent=4,
187 ... options={doctest.ELLIPSIS: True})
188 >>> (example.source, example.want, example.exc_msg,
189 ... example.lineno, example.indent, example.options)
190 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
191
192The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000193
Tim Petersbb431472004-08-09 03:51:46 +0000194 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000195 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000196 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000197 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000198
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000199 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000200 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000201 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000202
Tim Petersbb431472004-08-09 03:51:46 +0000203 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000204 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000205 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000206 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000207
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000208 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000209 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000210 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000211
Edward Lopera6b68322004-08-26 00:05:43 +0000212 Empty source string (which should never appear in real examples)
213 >>> e = doctest.Example('', '')
214 >>> e.source, e.want
215 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000216
Edward Lopera6b68322004-08-26 00:05:43 +0000217The constructor normalizes the `want` string to end in a newline,
218unless it's the empty string:
219
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000220 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000221 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000222 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000223
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000224 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000225 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000226 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000227
Edward Lopera6b68322004-08-26 00:05:43 +0000228 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000229 >>> e.source, e.want
230 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000231
232The constructor normalizes the `exc_msg` string to end in a newline,
233unless it's `None`:
234
235 Message spans one line
236 >>> exc_msg = 'IndexError: pop from an empty list'
237 >>> e = doctest.Example('[].pop()', '', exc_msg)
238 >>> e.exc_msg
239 'IndexError: pop from an empty list\n'
240
241 >>> exc_msg = 'IndexError: pop from an empty list\n'
242 >>> e = doctest.Example('[].pop()', '', exc_msg)
243 >>> e.exc_msg
244 'IndexError: pop from an empty list\n'
245
246 Message spans multiple lines
247 >>> exc_msg = 'ValueError: 1\n 2'
248 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
249 >>> e.exc_msg
250 'ValueError: 1\n 2\n'
251
252 >>> exc_msg = 'ValueError: 1\n 2\n'
253 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
254 >>> e.exc_msg
255 'ValueError: 1\n 2\n'
256
257 Empty (but non-None) exception message (which should never appear
258 in real examples)
259 >>> exc_msg = ''
260 >>> e = doctest.Example('raise X()', '', exc_msg)
261 >>> e.exc_msg
262 '\n'
Antoine Pitrou165b1282011-12-18 20:20:17 +0100263
264Compare `Example`:
265 >>> example = doctest.Example('print 1', '1\n')
266 >>> same_example = doctest.Example('print 1', '1\n')
267 >>> other_example = doctest.Example('print 42', '42\n')
268 >>> example == same_example
269 True
270 >>> example != same_example
271 False
272 >>> hash(example) == hash(same_example)
273 True
274 >>> example == other_example
275 False
276 >>> example != other_example
277 True
Tim Peters8485b562004-08-04 18:46:34 +0000278"""
279
280def test_DocTest(): r"""
281Unit tests for the `DocTest` class.
282
283DocTest is a collection of examples, extracted from a docstring, along
284with information about where the docstring comes from (a name,
285filename, and line number). The docstring is parsed by the `DocTest`
286constructor:
287
288 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000289 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000290 ... 12
291 ...
292 ... Non-example text.
293 ...
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000294 ... >>> print('another\example')
Tim Peters8485b562004-08-04 18:46:34 +0000295 ... another
296 ... example
297 ... '''
298 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000299 >>> parser = doctest.DocTestParser()
300 >>> test = parser.get_doctest(docstring, globs, 'some_test',
301 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000302 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000303 <DocTest some_test from some_file:20 (2 examples)>
304 >>> len(test.examples)
305 2
306 >>> e1, e2 = test.examples
307 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000308 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000309 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000310 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000311
312Source information (name, filename, and line number) is available as
313attributes on the doctest object:
314
315 >>> (test.name, test.filename, test.lineno)
316 ('some_test', 'some_file', 20)
317
318The line number of an example within its containing file is found by
319adding the line number of the example and the line number of its
320containing test:
321
322 >>> test.lineno + e1.lineno
323 21
324 >>> test.lineno + e2.lineno
325 26
326
Martin Panter46f50722016-05-26 05:35:26 +0000327If the docstring contains inconsistent leading whitespace in the
Tim Peters8485b562004-08-04 18:46:34 +0000328expected output of an example, then `DocTest` will raise a ValueError:
329
330 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000331 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000332 ... bad
333 ... indentation
334 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000335 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000336 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000337 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000338
339If the docstring contains inconsistent leading whitespace on
340continuation lines, then `DocTest` will raise a ValueError:
341
342 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000343 ... >>> print(('bad indentation',
344 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000345 ... ('bad', 'indentation')
346 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000347 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000348 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000349 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000350
351If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
352will raise a ValueError:
353
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000354 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000355 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000356 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000357 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000358
359If there's no blank space after a PS2 prompt ('...'), then `DocTest`
360will raise a ValueError:
361
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000362 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000363 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000364 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000365 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000366
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100367Compare `DocTest`:
368
369 >>> docstring = '''
370 ... >>> print 12
371 ... 12
372 ... '''
373 >>> test = parser.get_doctest(docstring, globs, 'some_test',
374 ... 'some_test', 20)
375 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
376 ... 'some_test', 20)
377 >>> test == same_test
378 True
379 >>> test != same_test
380 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100381 >>> hash(test) == hash(same_test)
382 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100383 >>> docstring = '''
384 ... >>> print 42
385 ... 42
386 ... '''
387 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
388 ... 'other_file', 10)
389 >>> test == other_test
390 False
391 >>> test != other_test
392 True
393
394Compare `DocTestCase`:
395
396 >>> DocTestCase = doctest.DocTestCase
397 >>> test_case = DocTestCase(test)
398 >>> same_test_case = DocTestCase(same_test)
399 >>> other_test_case = DocTestCase(other_test)
400 >>> test_case == same_test_case
401 True
402 >>> test_case != same_test_case
403 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100404 >>> hash(test_case) == hash(same_test_case)
405 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100406 >>> test == other_test_case
407 False
408 >>> test != other_test_case
409 True
410
Tim Peters8485b562004-08-04 18:46:34 +0000411"""
412
Zachary Ware7119b452013-11-24 02:21:57 -0600413class test_DocTestFinder:
414 def basics(): r"""
Tim Peters8485b562004-08-04 18:46:34 +0000415Unit tests for the `DocTestFinder` class.
416
417DocTestFinder is used to extract DocTests from an object's docstring
418and the docstrings of its contained objects. It can be used with
419modules, functions, classes, methods, staticmethods, classmethods, and
420properties.
421
422Finding Tests in Functions
423~~~~~~~~~~~~~~~~~~~~~~~~~~
424For a function whose docstring contains examples, DocTestFinder.find()
425will return a single test (for that function's docstring):
426
Tim Peters8485b562004-08-04 18:46:34 +0000427 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000428
429We'll simulate a __file__ attr that ends in pyc:
430
431 >>> import test.test_doctest
432 >>> old = test.test_doctest.__file__
433 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
434
Tim Peters8485b562004-08-04 18:46:34 +0000435 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000436
Guido van Rossum7131f842007-02-09 20:13:25 +0000437 >>> print(tests) # doctest: +ELLIPSIS
Yury Selivanovb532df62014-12-08 15:00:05 -0500438 [<DocTest sample_func from ...:19 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000439
Tim Peters4de7c5c2004-08-23 22:38:05 +0000440The exact name depends on how test_doctest was invoked, so allow for
441leading path components.
442
443 >>> tests[0].filename # doctest: +ELLIPSIS
444 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000445
446 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000447
Jim Fulton07a349c2004-08-22 14:10:00 +0000448
Tim Peters8485b562004-08-04 18:46:34 +0000449 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000450 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000451 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000452
Edward Loper32ddbf72004-09-13 05:47:24 +0000453By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000454
455 >>> def no_docstring(v):
456 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000457 >>> finder.find(no_docstring)
458 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000459
460However, the optional argument `exclude_empty` to the DocTestFinder
461constructor can be used to exclude tests for objects with empty
462docstrings:
463
464 >>> def no_docstring(v):
465 ... pass
466 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
467 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000468 []
469
470If the function has a docstring with no examples, then a test with no
471examples is returned. (This lets `DocTestRunner` collect statistics
472about which functions have no tests -- but is that useful? And should
473an empty test also be created when there's no docstring?)
474
475 >>> def no_examples(v):
476 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000477 >>> finder.find(no_examples) # doctest: +ELLIPSIS
478 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000479
480Finding Tests in Classes
481~~~~~~~~~~~~~~~~~~~~~~~~
482For a class, DocTestFinder will create a test for the class's
483docstring, and will recursively explore its contents, including
484methods, classmethods, staticmethods, properties, and nested classes.
485
486 >>> finder = doctest.DocTestFinder()
487 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000488 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000489 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000490 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000491 3 SampleClass.NestedClass
492 1 SampleClass.NestedClass.__init__
493 1 SampleClass.__init__
494 2 SampleClass.a_classmethod
495 1 SampleClass.a_property
496 1 SampleClass.a_staticmethod
497 1 SampleClass.double
498 1 SampleClass.get
499
500New-style classes are also supported:
501
502 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000503 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000504 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000505 1 SampleNewStyleClass
506 1 SampleNewStyleClass.__init__
507 1 SampleNewStyleClass.double
508 1 SampleNewStyleClass.get
509
510Finding Tests in Modules
511~~~~~~~~~~~~~~~~~~~~~~~~
512For a module, DocTestFinder will create a test for the class's
513docstring, and will recursively explore its contents, including
514functions, classes, and the `__test__` dictionary, if it exists:
515
516 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000517 >>> import types
518 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000519 >>> def triple(val):
520 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000521 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000522 ... 33
523 ... '''
524 ... return val*3
525 >>> m.__dict__.update({
526 ... 'sample_func': sample_func,
527 ... 'SampleClass': SampleClass,
528 ... '__doc__': '''
529 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000530 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000531 ... module
532 ... ''',
533 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000534 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000535 ... 'c': triple}})
536
537 >>> finder = doctest.DocTestFinder()
538 >>> # Use module=test.test_doctest, to prevent doctest from
539 >>> # ignoring the objects since they weren't defined in m.
540 >>> import test.test_doctest
541 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000542 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000543 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000544 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000545 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000546 3 some_module.SampleClass.NestedClass
547 1 some_module.SampleClass.NestedClass.__init__
548 1 some_module.SampleClass.__init__
549 2 some_module.SampleClass.a_classmethod
550 1 some_module.SampleClass.a_property
551 1 some_module.SampleClass.a_staticmethod
552 1 some_module.SampleClass.double
553 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000554 1 some_module.__test__.c
555 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000556 1 some_module.sample_func
557
558Duplicate Removal
559~~~~~~~~~~~~~~~~~
560If a single object is listed twice (under different names), then tests
561will only be generated for it once:
562
Tim Petersf3f57472004-08-08 06:11:48 +0000563 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000564 >>> assert doctest_aliases.TwoNames.f
565 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000566 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000567 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000568 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000569 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000570 test.doctest_aliases.TwoNames
571
572 TwoNames.f and TwoNames.g are bound to the same object.
573 We can't guess which will be found in doctest's traversal of
574 TwoNames.__dict__ first, so we have to allow for either.
575
576 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000577 True
578
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000579Empty Tests
580~~~~~~~~~~~
581By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000582
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000583 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000584 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000585 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000586 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000587 3 SampleClass.NestedClass
588 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000589 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000590 2 SampleClass.a_classmethod
591 1 SampleClass.a_property
592 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000593 1 SampleClass.double
594 1 SampleClass.get
595
596By default, that excluded objects with no doctests. exclude_empty=False
597tells it to include (empty) tests for objects with no doctests. This feature
598is really to support backward compatibility in what doctest.master.summarize()
599displays.
600
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000601 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000602 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000603 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000604 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000605 3 SampleClass.NestedClass
606 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000607 0 SampleClass.NestedClass.get
608 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000609 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000610 2 SampleClass.a_classmethod
611 1 SampleClass.a_property
612 1 SampleClass.a_staticmethod
613 1 SampleClass.double
614 1 SampleClass.get
615
Tim Peters8485b562004-08-04 18:46:34 +0000616Turning off Recursion
617~~~~~~~~~~~~~~~~~~~~~
618DocTestFinder can be told not to look for tests in contained objects
619using the `recurse` flag:
620
621 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000622 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000623 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000624 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000625
626Line numbers
627~~~~~~~~~~~~
628DocTestFinder finds the line number of each example:
629
630 >>> def f(x):
631 ... '''
632 ... >>> x = 12
633 ...
634 ... some text
635 ...
636 ... >>> # examples are not created for comments & bare prompts.
637 ... >>>
638 ... ...
639 ...
640 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000641 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000642 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000643 ... >>> x//2
644 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000645 ... '''
646 >>> test = doctest.DocTestFinder().find(f)[0]
647 >>> [e.lineno for e in test.examples]
648 [1, 9, 12]
Zachary Ware7119b452013-11-24 02:21:57 -0600649"""
650
651 if int.__doc__: # simple check for --without-doc-strings, skip if lacking
652 def non_Python_modules(): r"""
Zachary Warea4b7a752013-11-24 01:19:09 -0600653
654Finding Doctests in Modules Not Written in Python
655~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
656DocTestFinder can also find doctests in most modules not written in Python.
657We'll use builtins as an example, since it almost certainly isn't written in
658plain ol' Python and is guaranteed to be available.
659
660 >>> import builtins
661 >>> tests = doctest.DocTestFinder().find(builtins)
Gregory P. Smith8cb65692015-04-25 23:22:26 +0000662 >>> 790 < len(tests) < 810 # approximate number of objects with docstrings
Zachary Ware7119b452013-11-24 02:21:57 -0600663 True
Zachary Warea4b7a752013-11-24 01:19:09 -0600664 >>> real_tests = [t for t in tests if len(t.examples) > 0]
Zachary Ware7119b452013-11-24 02:21:57 -0600665 >>> len(real_tests) # objects that actually have doctests
Zachary Warea4b7a752013-11-24 01:19:09 -0600666 8
667 >>> for t in real_tests:
668 ... print('{} {}'.format(len(t.examples), t.name))
669 ...
670 1 builtins.bin
671 3 builtins.float.as_integer_ratio
672 2 builtins.float.fromhex
673 2 builtins.float.hex
674 1 builtins.hex
675 1 builtins.int
676 2 builtins.int.bit_length
677 1 builtins.oct
678
679Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
680'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
681and 'int' is a type.
Tim Peters8485b562004-08-04 18:46:34 +0000682"""
683
Edward Loper00f8da72004-08-26 18:05:07 +0000684def test_DocTestParser(): r"""
685Unit tests for the `DocTestParser` class.
686
687DocTestParser is used to parse docstrings containing doctest examples.
688
689The `parse` method divides a docstring into examples and intervening
690text:
691
692 >>> s = '''
693 ... >>> x, y = 2, 3 # no output expected
694 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000695 ... ... print(x)
696 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000697 ... 2
698 ... 3
699 ...
700 ... Some text.
701 ... >>> x+y
702 ... 5
703 ... '''
704 >>> parser = doctest.DocTestParser()
705 >>> for piece in parser.parse(s):
706 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000707 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000708 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000709 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000710 Text: '\n'
711 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
712 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000713 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000714 Text: '\nSome text.\n'
715 Example: ('x+y\n', '5\n', 9)
716 Text: ''
717
718The `get_examples` method returns just the examples:
719
720 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000721 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000722 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000723 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000724 ('x+y\n', '5\n', 9)
725
726The `get_doctest` method creates a Test from the examples, along with the
727given arguments:
728
729 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
730 >>> (test.name, test.filename, test.lineno)
731 ('name', 'filename', 5)
732 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000733 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000734 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000735 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000736 ('x+y\n', '5\n', 9)
737"""
738
Tim Peters8485b562004-08-04 18:46:34 +0000739class test_DocTestRunner:
740 def basics(): r"""
741Unit tests for the `DocTestRunner` class.
742
743DocTestRunner is used to run DocTest test cases, and to accumulate
744statistics. Here's a simple DocTest case we can use:
745
746 >>> def f(x):
747 ... '''
748 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000749 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000750 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000751 ... >>> x//2
752 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000753 ... '''
754 >>> test = doctest.DocTestFinder().find(f)[0]
755
756The main DocTestRunner interface is the `run` method, which runs a
757given DocTest case in a given namespace (globs). It returns a tuple
758`(f,t)`, where `f` is the number of failed tests and `t` is the number
759of tried tests.
760
761 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000762 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000763
764If any example produces incorrect output, then the test runner reports
765the failure and proceeds to the next example:
766
767 >>> def f(x):
768 ... '''
769 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000770 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000771 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000772 ... >>> x//2
773 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000774 ... '''
775 >>> test = doctest.DocTestFinder().find(f)[0]
776 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000777 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000778 Trying:
779 x = 12
780 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000781 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000782 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000783 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000784 Expecting:
785 14
Tim Peters8485b562004-08-04 18:46:34 +0000786 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000787 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000788 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000789 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000790 Expected:
791 14
792 Got:
793 12
Edward Loperaacf0832004-08-26 01:19:50 +0000794 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000795 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000796 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000797 6
Tim Peters8485b562004-08-04 18:46:34 +0000798 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000799 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000800"""
801 def verbose_flag(): r"""
802The `verbose` flag makes the test runner generate more detailed
803output:
804
805 >>> def f(x):
806 ... '''
807 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000808 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000809 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000810 ... >>> x//2
811 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000812 ... '''
813 >>> test = doctest.DocTestFinder().find(f)[0]
814
815 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000816 Trying:
817 x = 12
818 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000819 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000820 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000821 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000822 Expecting:
823 12
Tim Peters8485b562004-08-04 18:46:34 +0000824 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000825 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000827 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000828 6
Tim Peters8485b562004-08-04 18:46:34 +0000829 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000830 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000831
832If the `verbose` flag is unspecified, then the output will be verbose
833iff `-v` appears in sys.argv:
834
835 >>> # Save the real sys.argv list.
836 >>> old_argv = sys.argv
837
838 >>> # If -v does not appear in sys.argv, then output isn't verbose.
839 >>> sys.argv = ['test']
840 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000841 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000842
843 >>> # If -v does appear in sys.argv, then output is verbose.
844 >>> sys.argv = ['test', '-v']
845 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000846 Trying:
847 x = 12
848 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000849 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000850 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000851 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000852 Expecting:
853 12
Tim Peters8485b562004-08-04 18:46:34 +0000854 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000855 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000856 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000857 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000858 6
Tim Peters8485b562004-08-04 18:46:34 +0000859 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000860 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000861
862 >>> # Restore sys.argv
863 >>> sys.argv = old_argv
864
865In the remaining examples, the test runner's verbosity will be
866explicitly set, to ensure that the test behavior is consistent.
867 """
868 def exceptions(): r"""
869Tests of `DocTestRunner`'s exception handling.
870
871An expected exception is specified with a traceback message. The
872lines between the first line and the type/value may be omitted or
873replaced with any other string:
874
875 >>> def f(x):
876 ... '''
877 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000878 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000879 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000880 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000881 ... '''
882 >>> test = doctest.DocTestFinder().find(f)[0]
883 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000884 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000885
Edward Loper19b19582004-08-25 23:07:03 +0000886An example may not generate output before it raises an exception; if
887it does, then the traceback message will not be recognized as
888signaling an expected exception, so the example will be reported as an
889unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000890
891 >>> def f(x):
892 ... '''
893 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000894 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000895 ... pre-exception output
896 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000897 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000898 ... '''
899 >>> test = doctest.DocTestFinder().find(f)[0]
900 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000901 ... # doctest: +ELLIPSIS
902 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000903 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000904 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000905 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000906 Exception raised:
907 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000908 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000909 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000910
911Exception messages may contain newlines:
912
913 >>> def f(x):
914 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000915 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000916 ... Traceback (most recent call last):
917 ... ValueError: multi
918 ... line
919 ... message
920 ... '''
921 >>> test = doctest.DocTestFinder().find(f)[0]
922 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000923 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000924
925If an exception is expected, but an exception with the wrong type or
926message is raised, then it is reported as a failure:
927
928 >>> def f(x):
929 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000930 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000931 ... Traceback (most recent call last):
932 ... ValueError: wrong message
933 ... '''
934 >>> test = doctest.DocTestFinder().find(f)[0]
935 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000936 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000937 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000938 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000939 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000940 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000941 Expected:
942 Traceback (most recent call last):
943 ValueError: wrong message
944 Got:
945 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000946 ...
Tim Peters8485b562004-08-04 18:46:34 +0000947 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000948 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000949
Tim Peters1fbf9c52004-09-04 17:21:02 +0000950However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
951detail:
952
953 >>> def f(x):
954 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000955 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000956 ... Traceback (most recent call last):
957 ... ValueError: wrong message
958 ... '''
959 >>> test = doctest.DocTestFinder().find(f)[0]
960 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000961 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000962
Nick Coghlan5e76e942010-06-12 13:42:46 +0000963IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
964between Python versions. For example, in Python 2.x, the module path of
965the exception is not in the output, but this will fail under Python 3:
966
967 >>> def f(x):
968 ... r'''
969 ... >>> from http.client import HTTPException
970 ... >>> raise HTTPException('message')
971 ... Traceback (most recent call last):
972 ... HTTPException: message
973 ... '''
974 >>> test = doctest.DocTestFinder().find(f)[0]
975 >>> doctest.DocTestRunner(verbose=False).run(test)
976 ... # doctest: +ELLIPSIS
977 **********************************************************************
978 File ..., line 4, in f
979 Failed example:
980 raise HTTPException('message')
981 Expected:
982 Traceback (most recent call last):
983 HTTPException: message
984 Got:
985 Traceback (most recent call last):
986 ...
987 http.client.HTTPException: message
988 TestResults(failed=1, attempted=2)
989
990But in Python 3 the module path is included, and therefore a test must look
991like the following test to succeed in Python 3. But that test will fail under
992Python 2.
993
994 >>> def f(x):
995 ... r'''
996 ... >>> from http.client import HTTPException
997 ... >>> raise HTTPException('message')
998 ... Traceback (most recent call last):
999 ... http.client.HTTPException: message
1000 ... '''
1001 >>> test = doctest.DocTestFinder().find(f)[0]
1002 >>> doctest.DocTestRunner(verbose=False).run(test)
1003 TestResults(failed=0, attempted=2)
1004
1005However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1006(or its unexpected absence) will be ignored:
1007
1008 >>> def f(x):
1009 ... r'''
1010 ... >>> from http.client import HTTPException
1011 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1012 ... Traceback (most recent call last):
1013 ... HTTPException: message
1014 ... '''
1015 >>> test = doctest.DocTestFinder().find(f)[0]
1016 >>> doctest.DocTestRunner(verbose=False).run(test)
1017 TestResults(failed=0, attempted=2)
1018
1019The module path will be completely ignored, so two different module paths will
1020still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1021be used when exceptions have changed module.
1022
1023 >>> def f(x):
1024 ... r'''
1025 ... >>> from http.client import HTTPException
1026 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1027 ... Traceback (most recent call last):
1028 ... foo.bar.HTTPException: message
1029 ... '''
1030 >>> test = doctest.DocTestFinder().find(f)[0]
1031 >>> doctest.DocTestRunner(verbose=False).run(test)
1032 TestResults(failed=0, attempted=2)
1033
Tim Peters1fbf9c52004-09-04 17:21:02 +00001034But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1035
1036 >>> def f(x):
1037 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001038 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001039 ... Traceback (most recent call last):
1040 ... TypeError: wrong type
1041 ... '''
1042 >>> test = doctest.DocTestFinder().find(f)[0]
1043 >>> doctest.DocTestRunner(verbose=False).run(test)
1044 ... # doctest: +ELLIPSIS
1045 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001046 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001047 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001048 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001049 Expected:
1050 Traceback (most recent call last):
1051 TypeError: wrong type
1052 Got:
1053 Traceback (most recent call last):
1054 ...
1055 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001056 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001057
Tim Petersf9a07f22013-12-03 21:02:05 -06001058If the exception does not have a message, you can still use
1059IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1060
1061 >>> def f(x):
1062 ... r'''
1063 ... >>> from http.client import HTTPException
1064 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1065 ... Traceback (most recent call last):
1066 ... foo.bar.HTTPException
1067 ... '''
1068 >>> test = doctest.DocTestFinder().find(f)[0]
1069 >>> doctest.DocTestRunner(verbose=False).run(test)
1070 TestResults(failed=0, attempted=2)
1071
1072Note that a trailing colon doesn't matter either:
1073
1074 >>> def f(x):
1075 ... r'''
1076 ... >>> from http.client import HTTPException
1077 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1078 ... Traceback (most recent call last):
1079 ... foo.bar.HTTPException:
1080 ... '''
1081 >>> test = doctest.DocTestFinder().find(f)[0]
1082 >>> doctest.DocTestRunner(verbose=False).run(test)
1083 TestResults(failed=0, attempted=2)
1084
Tim Peters8485b562004-08-04 18:46:34 +00001085If an exception is raised but not expected, then it is reported as an
1086unexpected exception:
1087
Tim Peters8485b562004-08-04 18:46:34 +00001088 >>> def f(x):
1089 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001090 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001091 ... 0
1092 ... '''
1093 >>> test = doctest.DocTestFinder().find(f)[0]
1094 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001095 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001096 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001097 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001098 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001099 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001100 Exception raised:
1101 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001102 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001103 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001104 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001105"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001106 def displayhook(): r"""
1107Test that changing sys.displayhook doesn't matter for doctest.
1108
1109 >>> import sys
1110 >>> orig_displayhook = sys.displayhook
1111 >>> def my_displayhook(x):
1112 ... print('hi!')
1113 >>> sys.displayhook = my_displayhook
1114 >>> def f():
1115 ... '''
1116 ... >>> 3
1117 ... 3
1118 ... '''
1119 >>> test = doctest.DocTestFinder().find(f)[0]
1120 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1121 >>> post_displayhook = sys.displayhook
1122
1123 We need to restore sys.displayhook now, so that we'll be able to test
1124 results.
1125
1126 >>> sys.displayhook = orig_displayhook
1127
1128 Ok, now we can check that everything is ok.
1129
1130 >>> r
1131 TestResults(failed=0, attempted=1)
1132 >>> post_displayhook is my_displayhook
1133 True
1134"""
Tim Peters8485b562004-08-04 18:46:34 +00001135 def optionflags(): r"""
1136Tests of `DocTestRunner`'s option flag handling.
1137
1138Several option flags can be used to customize the behavior of the test
1139runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001140to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001141together).
1142
1143The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1144and 1/0:
1145
1146 >>> def f(x):
1147 ... '>>> True\n1\n'
1148
1149 >>> # Without the flag:
1150 >>> test = doctest.DocTestFinder().find(f)[0]
1151 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001152 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001153
1154 >>> # With the flag:
1155 >>> test = doctest.DocTestFinder().find(f)[0]
1156 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1157 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001158 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001159 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001160 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001161 Failed example:
1162 True
1163 Expected:
1164 1
1165 Got:
1166 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001167 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001168
1169The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1170and the '<BLANKLINE>' marker:
1171
1172 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001173 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001174
1175 >>> # Without the flag:
1176 >>> test = doctest.DocTestFinder().find(f)[0]
1177 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001178 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001179
1180 >>> # With the flag:
1181 >>> test = doctest.DocTestFinder().find(f)[0]
1182 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1183 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001184 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001185 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001186 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001187 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001188 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001189 Expected:
1190 a
1191 <BLANKLINE>
1192 b
1193 Got:
1194 a
1195 <BLANKLINE>
1196 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001197 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001198
1199The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1200treated as equal:
1201
1202 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001203 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001204
1205 >>> # Without the flag:
1206 >>> test = doctest.DocTestFinder().find(f)[0]
1207 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001208 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001209 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001210 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001211 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001212 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001213 Expected:
1214 1 2
1215 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001216 Got:
1217 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001218 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001219
1220 >>> # With the flag:
1221 >>> test = doctest.DocTestFinder().find(f)[0]
1222 >>> flags = doctest.NORMALIZE_WHITESPACE
1223 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001224 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001225
Tim Peters026f8dc2004-08-19 16:38:58 +00001226 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001227 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001228 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1229 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1230
Tim Peters8485b562004-08-04 18:46:34 +00001231The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1232output to match any substring in the actual output:
1233
1234 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001235 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001236
1237 >>> # Without the flag:
1238 >>> test = doctest.DocTestFinder().find(f)[0]
1239 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001240 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001241 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001242 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001243 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001244 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001245 Expected:
1246 [0, 1, 2, ..., 14]
1247 Got:
1248 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001249 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001250
1251 >>> # With the flag:
1252 >>> test = doctest.DocTestFinder().find(f)[0]
1253 >>> flags = doctest.ELLIPSIS
1254 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001255 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001256
Tim Peterse594bee2004-08-22 01:47:51 +00001257 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001258
Guido van Rossume0192e52007-02-09 23:39:59 +00001259 >>> if 1:
1260 ... for i in range(100):
1261 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1262 ... print('!')
1263 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001264
Tim Peters026f8dc2004-08-19 16:38:58 +00001265 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001266
Guido van Rossume0192e52007-02-09 23:39:59 +00001267 >>> if 1: #doctest: +ELLIPSIS
1268 ... for i in range(20):
1269 ... print(i, end=' ')
1270 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001271 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001272
Tim Peters026f8dc2004-08-19 16:38:58 +00001273 Examples from the docs:
1274
Guido van Rossum805365e2007-05-07 22:24:25 +00001275 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001276 [0, 1, ..., 18, 19]
1277
Guido van Rossum805365e2007-05-07 22:24:25 +00001278 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001279 ... # doctest: +NORMALIZE_WHITESPACE
1280 [0, 1, ..., 18, 19]
1281
Thomas Wouters477c8d52006-05-27 19:21:47 +00001282The SKIP flag causes an example to be skipped entirely. I.e., the
1283example is not run. It can be useful in contexts where doctest
1284examples serve as both documentation and test cases, and an example
1285should be included for documentation purposes, but should not be
1286checked (e.g., because its output is random, or depends on resources
1287which would be unavailable.) The SKIP flag can also be used for
1288'commenting out' broken examples.
1289
1290 >>> import unavailable_resource # doctest: +SKIP
1291 >>> unavailable_resource.do_something() # doctest: +SKIP
1292 >>> unavailable_resource.blow_up() # doctest: +SKIP
1293 Traceback (most recent call last):
1294 ...
1295 UncheckedBlowUpError: Nobody checks me.
1296
1297 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001298 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001299 0.721216923889
1300
Edward Loper71f55af2004-08-26 01:41:51 +00001301The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001302and actual outputs to be displayed using a unified diff:
1303
1304 >>> def f(x):
1305 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001306 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001307 ... a
1308 ... B
1309 ... c
1310 ... d
1311 ... f
1312 ... g
1313 ... h
1314 ... '''
1315
1316 >>> # Without the flag:
1317 >>> test = doctest.DocTestFinder().find(f)[0]
1318 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001319 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001320 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001321 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001322 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001323 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001324 Expected:
1325 a
1326 B
1327 c
1328 d
1329 f
1330 g
1331 h
1332 Got:
1333 a
1334 b
1335 c
1336 d
1337 e
1338 f
1339 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001340 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001341
1342 >>> # With the flag:
1343 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001344 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001345 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001346 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001347 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001348 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001349 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001350 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001351 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001352 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001353 a
1354 -B
1355 +b
1356 c
1357 d
1358 +e
1359 f
1360 g
1361 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001362 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001363
Edward Loper71f55af2004-08-26 01:41:51 +00001364The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001365and actual outputs to be displayed using a context diff:
1366
Edward Loper71f55af2004-08-26 01:41:51 +00001367 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001368 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001369 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001370 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001371 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001372 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001373 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001374 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001375 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001376 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001377 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001378 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001379 a
1380 ! B
1381 c
1382 d
1383 f
1384 g
1385 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001386 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001387 a
1388 ! b
1389 c
1390 d
1391 + e
1392 f
1393 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001394 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001395
1396
Edward Loper71f55af2004-08-26 01:41:51 +00001397The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001398used by the popular ndiff.py utility. This does intraline difference
1399marking, as well as interline differences.
1400
1401 >>> def f(x):
1402 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001403 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001404 ... a b c d e f g h i j k 1 m
1405 ... '''
1406 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001407 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001408 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001409 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001410 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001411 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001412 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001413 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001414 Differences (ndiff with -expected +actual):
1415 - a b c d e f g h i j k 1 m
1416 ? ^
1417 + a b c d e f g h i j k l m
1418 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001419 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001420
Ezio Melotti13925002011-03-16 11:05:33 +02001421The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001422failing example:
1423
1424 >>> def f(x):
1425 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001426 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001427 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001428 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001429 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001430 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001431 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001432 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001433 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001434 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001435 ... 500
1436 ... '''
1437 >>> test = doctest.DocTestFinder().find(f)[0]
1438 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1439 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001440 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001441 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001442 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001443 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001444 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001445 Expected:
1446 200
1447 Got:
1448 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001449 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001450
Ezio Melotti13925002011-03-16 11:05:33 +02001451However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001452
1453 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001454 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001455 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001456 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001457 Expecting:
1458 1
1459 ok
1460 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001461 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001462 Expecting:
1463 200
1464 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001465 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001466 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001467 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001468 Expected:
1469 200
1470 Got:
1471 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001472 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001473
R David Murray5a9d7062012-11-21 15:09:21 -05001474The FAIL_FAST flag causes the runner to exit after the first failing example,
1475so subsequent examples are not even attempted:
1476
1477 >>> flags = doctest.FAIL_FAST
1478 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1479 ... # doctest: +ELLIPSIS
1480 **********************************************************************
1481 File ..., line 5, in f
1482 Failed example:
1483 print(2) # first failure
1484 Expected:
1485 200
1486 Got:
1487 2
1488 TestResults(failed=1, attempted=2)
1489
1490Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1491FAIL_FAST only:
1492
1493 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1494 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1495 ... # doctest: +ELLIPSIS
1496 **********************************************************************
1497 File ..., line 5, in f
1498 Failed example:
1499 print(2) # first failure
1500 Expected:
1501 200
1502 Got:
1503 2
1504 TestResults(failed=1, attempted=2)
1505
1506For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1507exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001508
1509 >>> def f(x):
1510 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001511 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001512 ... 1
1513 ... >>> raise ValueError(2) # first failure
1514 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001515 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001516 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001517 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001518 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001519 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001520 ... 500
1521 ... '''
1522 >>> test = doctest.DocTestFinder().find(f)[0]
1523 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1524 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1525 ... # doctest: +ELLIPSIS
1526 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001527 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001528 Failed example:
1529 raise ValueError(2) # first failure
1530 Exception raised:
1531 ...
1532 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001533 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001534 >>> flags = doctest.FAIL_FAST
1535 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1536 ... # doctest: +ELLIPSIS
1537 **********************************************************************
1538 File ..., line 5, in f
1539 Failed example:
1540 raise ValueError(2) # first failure
1541 Exception raised:
1542 ...
1543 ValueError: 2
1544 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001545
Thomas Wouters477c8d52006-05-27 19:21:47 +00001546New option flags can also be registered, via register_optionflag(). Here
1547we reach into doctest's internals a bit.
1548
1549 >>> unlikely = "UNLIKELY_OPTION_NAME"
1550 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1551 False
1552 >>> new_flag_value = doctest.register_optionflag(unlikely)
1553 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1554 True
1555
1556Before 2.4.4/2.5, registering a name more than once erroneously created
1557more than one flag value. Here we verify that's fixed:
1558
1559 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1560 >>> redundant_flag_value == new_flag_value
1561 True
1562
1563Clean up.
1564 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1565
Tim Petersc6cbab02004-08-22 19:43:28 +00001566 """
1567
Tim Peters8485b562004-08-04 18:46:34 +00001568 def option_directives(): r"""
1569Tests of `DocTestRunner`'s option directive mechanism.
1570
Edward Loper74bca7a2004-08-12 02:27:44 +00001571Option directives can be used to turn option flags on or off for a
1572single example. To turn an option on for an example, follow that
1573example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001574
1575 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001576 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001577 ... [0, 1, ..., 9]
1578 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001579 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001580 ... [0, 1, ..., 9]
1581 ... '''
1582 >>> test = doctest.DocTestFinder().find(f)[0]
1583 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001584 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001585 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001586 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001587 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001588 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001589 Expected:
1590 [0, 1, ..., 9]
1591 Got:
1592 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001593 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001594
1595To turn an option off for an example, follow that example with a
1596comment of the form ``# doctest: -OPTION``:
1597
1598 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001599 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001600 ... [0, 1, ..., 9]
1601 ...
1602 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001603 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001604 ... [0, 1, ..., 9]
1605 ... '''
1606 >>> test = doctest.DocTestFinder().find(f)[0]
1607 >>> doctest.DocTestRunner(verbose=False,
1608 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001609 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001610 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001611 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001612 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001613 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001614 Expected:
1615 [0, 1, ..., 9]
1616 Got:
1617 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001618 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001619
1620Option directives affect only the example that they appear with; they
1621do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001622
Edward Loper74bca7a2004-08-12 02:27:44 +00001623 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001624 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001625 ... [0, 1, ..., 9]
1626 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001627 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001628 ... [0, 1, ..., 9]
1629 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001630 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001631 ... [0, 1, ..., 9]
1632 ... '''
1633 >>> test = doctest.DocTestFinder().find(f)[0]
1634 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001635 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001636 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001637 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001638 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001639 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001640 Expected:
1641 [0, 1, ..., 9]
1642 Got:
1643 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001644 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001645 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001646 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001647 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001648 Expected:
1649 [0, 1, ..., 9]
1650 Got:
1651 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001652 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001653
Edward Loper74bca7a2004-08-12 02:27:44 +00001654Multiple options may be modified by a single option directive. They
1655may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001656
1657 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001658 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001659 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001660 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001661 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001662 ... [0, 1, ..., 9]
1663 ... '''
1664 >>> test = doctest.DocTestFinder().find(f)[0]
1665 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001666 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001667 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001668 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001669 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001670 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001671 Expected:
1672 [0, 1, ..., 9]
1673 Got:
1674 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001675 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001676
1677 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001678 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001679 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001680 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001681 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1682 ... [0, 1, ..., 9]
1683 ... '''
1684 >>> test = doctest.DocTestFinder().find(f)[0]
1685 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001686 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001687 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001688 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001689 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001690 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001691 Expected:
1692 [0, 1, ..., 9]
1693 Got:
1694 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001695 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001696
1697 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001698 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001699 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001700 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001701 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1702 ... [0, 1, ..., 9]
1703 ... '''
1704 >>> test = doctest.DocTestFinder().find(f)[0]
1705 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001706 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001707 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001708 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001709 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001710 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001711 Expected:
1712 [0, 1, ..., 9]
1713 Got:
1714 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001715 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001716
1717The option directive may be put on the line following the source, as
1718long as a continuation prompt is used:
1719
1720 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001721 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001722 ... ... # doctest: +ELLIPSIS
1723 ... [0, 1, ..., 9]
1724 ... '''
1725 >>> test = doctest.DocTestFinder().find(f)[0]
1726 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001727 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001728
Edward Loper74bca7a2004-08-12 02:27:44 +00001729For examples with multi-line source, the option directive may appear
1730at the end of any line:
1731
1732 >>> def f(x): r'''
1733 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001734 ... ... print(' ', x, end='', sep='')
1735 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001736 ...
1737 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001738 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1739 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001740 ... '''
1741 >>> test = doctest.DocTestFinder().find(f)[0]
1742 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001743 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001744
1745If more than one line of an example with multi-line source has an
1746option directive, then they are combined:
1747
1748 >>> def f(x): r'''
1749 ... Should fail (option directive not on the last line):
1750 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001751 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001752 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001753 ... '''
1754 >>> test = doctest.DocTestFinder().find(f)[0]
1755 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001756 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001757
1758It is an error to have a comment of the form ``# doctest:`` that is
1759*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1760``OPTION`` is an option that has been registered with
1761`register_option`:
1762
1763 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001764 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001765 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1766 Traceback (most recent call last):
1767 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1768
1769 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001770 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001771 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1772 Traceback (most recent call last):
1773 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1774
1775It is an error to use an option directive on a line that contains no
1776source:
1777
1778 >>> s = '>>> # doctest: +ELLIPSIS'
1779 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1780 Traceback (most recent call last):
1781 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 +00001782"""
1783
1784def test_testsource(): r"""
1785Unit tests for `testsource()`.
1786
1787The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001788test with that name in that module, and converts it to a script. The
1789example code is converted to regular Python code. The surrounding
1790words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001791
1792 >>> import test.test_doctest
1793 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001794 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001795 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001796 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001797 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001798 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001799 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001800 #
Edward Lopera5db6002004-08-12 02:41:30 +00001801 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001802 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001803
1804 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001805 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001806 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001807 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001808 ## 1
1809 ## 2
1810 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001811 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001812
1813 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001814 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001815 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001816 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001817 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001818 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001819 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001820 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001821 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001822"""
1823
1824def test_debug(): r"""
1825
1826Create a docstring that we want to debug:
1827
1828 >>> s = '''
1829 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001830 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001831 ... 12
1832 ... '''
1833
1834Create some fake stdin input, to feed to the debugger:
1835
Tim Peters8485b562004-08-04 18:46:34 +00001836 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001837 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001838
1839Run the debugger on the docstring, and then restore sys.stdin.
1840
Edward Loper2de91ba2004-08-27 02:07:46 +00001841 >>> try: doctest.debug_src(s)
1842 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001843 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001844 (Pdb) next
1845 12
Tim Peters8485b562004-08-04 18:46:34 +00001846 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001847 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001848 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001849 12
1850 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001851
1852"""
1853
Brett Cannon31f59292011-02-21 19:29:56 +00001854if not hasattr(sys, 'gettrace') or not sys.gettrace():
1855 def test_pdb_set_trace():
1856 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001857
Brett Cannon31f59292011-02-21 19:29:56 +00001858 You can use pdb.set_trace from a doctest. To do so, you must
1859 retrieve the set_trace function from the pdb module at the time
1860 you use it. The doctest module changes sys.stdout so that it can
1861 capture program output. It also temporarily replaces pdb.set_trace
1862 with a version that restores stdout. This is necessary for you to
1863 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001864
Brett Cannon31f59292011-02-21 19:29:56 +00001865 >>> doc = '''
1866 ... >>> x = 42
1867 ... >>> raise Exception('clé')
1868 ... Traceback (most recent call last):
1869 ... Exception: clé
1870 ... >>> import pdb; pdb.set_trace()
1871 ... '''
1872 >>> parser = doctest.DocTestParser()
1873 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1874 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001875
Brett Cannon31f59292011-02-21 19:29:56 +00001876 To demonstrate this, we'll create a fake standard input that
1877 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001878
Brett Cannon31f59292011-02-21 19:29:56 +00001879 >>> import tempfile
1880 >>> real_stdin = sys.stdin
1881 >>> sys.stdin = _FakeInput([
1882 ... 'print(x)', # print data defined by the example
1883 ... 'continue', # stop debugging
1884 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001885
Brett Cannon31f59292011-02-21 19:29:56 +00001886 >>> try: runner.run(test)
1887 ... finally: sys.stdin = real_stdin
1888 --Return--
1889 > <doctest foo-bar@baz[2]>(1)<module>()->None
1890 -> import pdb; pdb.set_trace()
1891 (Pdb) print(x)
1892 42
1893 (Pdb) continue
1894 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001895
Brett Cannon31f59292011-02-21 19:29:56 +00001896 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001897
Brett Cannon31f59292011-02-21 19:29:56 +00001898 >>> def calls_set_trace():
1899 ... y=2
1900 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001901
Brett Cannon31f59292011-02-21 19:29:56 +00001902 >>> doc = '''
1903 ... >>> x=1
1904 ... >>> calls_set_trace()
1905 ... '''
1906 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1907 >>> real_stdin = sys.stdin
1908 >>> sys.stdin = _FakeInput([
1909 ... 'print(y)', # print data defined in the function
1910 ... 'up', # out of function
1911 ... 'print(x)', # print data defined by the example
1912 ... 'continue', # stop debugging
1913 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001914
Brett Cannon31f59292011-02-21 19:29:56 +00001915 >>> try:
1916 ... runner.run(test)
1917 ... finally:
1918 ... sys.stdin = real_stdin
1919 --Return--
1920 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1921 -> import pdb; pdb.set_trace()
1922 (Pdb) print(y)
1923 2
1924 (Pdb) up
1925 > <doctest foo-bar@baz[1]>(1)<module>()
1926 -> calls_set_trace()
1927 (Pdb) print(x)
1928 1
1929 (Pdb) continue
1930 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001931
Brett Cannon31f59292011-02-21 19:29:56 +00001932 During interactive debugging, source code is shown, even for
1933 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001934
Brett Cannon31f59292011-02-21 19:29:56 +00001935 >>> doc = '''
1936 ... >>> def f(x):
1937 ... ... g(x*2)
1938 ... >>> def g(x):
1939 ... ... print(x+3)
1940 ... ... import pdb; pdb.set_trace()
1941 ... >>> f(3)
1942 ... '''
1943 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1944 >>> real_stdin = sys.stdin
1945 >>> sys.stdin = _FakeInput([
1946 ... 'list', # list source from example 2
1947 ... 'next', # return from g()
1948 ... 'list', # list source from example 1
1949 ... 'next', # return from f()
1950 ... 'list', # list source from example 3
1951 ... 'continue', # stop debugging
1952 ... ''])
1953 >>> try: runner.run(test)
1954 ... finally: sys.stdin = real_stdin
1955 ... # doctest: +NORMALIZE_WHITESPACE
1956 --Return--
1957 > <doctest foo-bar@baz[1]>(3)g()->None
1958 -> import pdb; pdb.set_trace()
1959 (Pdb) list
1960 1 def g(x):
1961 2 print(x+3)
1962 3 -> import pdb; pdb.set_trace()
1963 [EOF]
1964 (Pdb) next
1965 --Return--
1966 > <doctest foo-bar@baz[0]>(2)f()->None
1967 -> g(x*2)
1968 (Pdb) list
1969 1 def f(x):
1970 2 -> g(x*2)
1971 [EOF]
1972 (Pdb) next
1973 --Return--
1974 > <doctest foo-bar@baz[2]>(1)<module>()->None
1975 -> f(3)
1976 (Pdb) list
1977 1 -> f(3)
1978 [EOF]
1979 (Pdb) continue
1980 **********************************************************************
1981 File "foo-bar@baz.py", line 7, in foo-bar@baz
1982 Failed example:
1983 f(3)
1984 Expected nothing
1985 Got:
1986 9
1987 TestResults(failed=1, attempted=3)
1988 """
Jim Fulton356fd192004-08-09 11:34:47 +00001989
Brett Cannon31f59292011-02-21 19:29:56 +00001990 def test_pdb_set_trace_nested():
1991 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00001992
Brett Cannon31f59292011-02-21 19:29:56 +00001993 >>> class C(object):
1994 ... def calls_set_trace(self):
1995 ... y = 1
1996 ... import pdb; pdb.set_trace()
1997 ... self.f1()
1998 ... y = 2
1999 ... def f1(self):
2000 ... x = 1
2001 ... self.f2()
2002 ... x = 2
2003 ... def f2(self):
2004 ... z = 1
2005 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002006
Brett Cannon31f59292011-02-21 19:29:56 +00002007 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002008
Brett Cannon31f59292011-02-21 19:29:56 +00002009 >>> doc = '''
2010 ... >>> a = 1
2011 ... >>> calls_set_trace()
2012 ... '''
2013 >>> parser = doctest.DocTestParser()
2014 >>> runner = doctest.DocTestRunner(verbose=False)
2015 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2016 >>> real_stdin = sys.stdin
2017 >>> sys.stdin = _FakeInput([
2018 ... 'print(y)', # print data defined in the function
2019 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2020 ... 'up', 'print(x)',
2021 ... 'up', 'print(y)',
2022 ... 'up', 'print(foo)',
2023 ... 'continue', # stop debugging
2024 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002025
Brett Cannon31f59292011-02-21 19:29:56 +00002026 >>> try:
2027 ... runner.run(test)
2028 ... finally:
2029 ... sys.stdin = real_stdin
2030 ... # doctest: +REPORT_NDIFF
2031 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2032 -> self.f1()
2033 (Pdb) print(y)
2034 1
2035 (Pdb) step
2036 --Call--
2037 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2038 -> def f1(self):
2039 (Pdb) step
2040 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2041 -> x = 1
2042 (Pdb) step
2043 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2044 -> self.f2()
2045 (Pdb) step
2046 --Call--
2047 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2048 -> def f2(self):
2049 (Pdb) step
2050 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2051 -> z = 1
2052 (Pdb) step
2053 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2054 -> z = 2
2055 (Pdb) print(z)
2056 1
2057 (Pdb) up
2058 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2059 -> self.f2()
2060 (Pdb) print(x)
2061 1
2062 (Pdb) up
2063 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2064 -> self.f1()
2065 (Pdb) print(y)
2066 1
2067 (Pdb) up
2068 > <doctest foo-bar@baz[1]>(1)<module>()
2069 -> calls_set_trace()
2070 (Pdb) print(foo)
2071 *** NameError: name 'foo' is not defined
2072 (Pdb) continue
2073 TestResults(failed=0, attempted=2)
2074 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002075
Tim Peters19397e52004-08-06 22:02:59 +00002076def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002077 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002078
2079 We create a Suite by providing a module. A module can be provided
2080 by passing a module object:
2081
2082 >>> import unittest
2083 >>> import test.sample_doctest
2084 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2085 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002086 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002087
2088 We can also supply the module by name:
2089
2090 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2091 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002092 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002093
R David Murray5abd76a2012-09-10 10:15:58 -04002094 The module need not contain any doctest examples:
2095
2096 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2097 >>> suite.run(unittest.TestResult())
2098 <unittest.result.TestResult run=0 errors=0 failures=0>
2099
R David Murray1976d9b2014-04-14 20:28:36 -04002100 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002101
R David Murray1976d9b2014-04-14 20:28:36 -04002102 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002103 >>> suite.run(unittest.TestResult())
2104 <unittest.result.TestResult run=0 errors=0 failures=0>
2105
Tim Peters19397e52004-08-06 22:02:59 +00002106 We can use the current module:
2107
2108 >>> suite = test.sample_doctest.test_suite()
2109 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002110 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002111
R David Murray1976d9b2014-04-14 20:28:36 -04002112 We can also provide a DocTestFinder:
2113
2114 >>> finder = doctest.DocTestFinder()
2115 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2116 ... test_finder=finder)
2117 >>> suite.run(unittest.TestResult())
2118 <unittest.result.TestResult run=9 errors=0 failures=4>
2119
2120 The DocTestFinder need not return any tests:
2121
2122 >>> finder = doctest.DocTestFinder()
2123 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2124 ... test_finder=finder)
2125 >>> suite.run(unittest.TestResult())
2126 <unittest.result.TestResult run=0 errors=0 failures=0>
2127
Tim Peters19397e52004-08-06 22:02:59 +00002128 We can supply global variables. If we pass globs, they will be
2129 used instead of the module globals. Here we'll pass an empty
2130 globals, triggering an extra error:
2131
2132 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2133 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002134 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002135
2136 Alternatively, we can provide extra globals. Here we'll make an
2137 error go away by providing an extra global variable:
2138
2139 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2140 ... extraglobs={'y': 1})
2141 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002142 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002143
2144 You can pass option flags. Here we'll cause an extra error
2145 by disabling the blank-line feature:
2146
2147 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002148 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002149 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002150 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002151
Tim Peters1e277ee2004-08-07 05:37:52 +00002152 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002153
Jim Fultonf54bad42004-08-28 14:57:56 +00002154 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002155 ... import test.test_doctest
2156 ... test.test_doctest.sillySetup = True
2157
Jim Fultonf54bad42004-08-28 14:57:56 +00002158 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002159 ... import test.test_doctest
2160 ... del test.test_doctest.sillySetup
2161
2162 Here, we installed a silly variable that the test expects:
2163
2164 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2165 ... setUp=setUp, tearDown=tearDown)
2166 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002167 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002168
2169 But the tearDown restores sanity:
2170
2171 >>> import test.test_doctest
2172 >>> test.test_doctest.sillySetup
2173 Traceback (most recent call last):
2174 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002175 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002176
Berker Peksag4882cac2015-04-14 09:30:01 +03002177 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002178 we'll use the setUp function to supply the missing variable y:
2179
2180 >>> def setUp(test):
2181 ... test.globs['y'] = 1
2182
2183 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2184 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002185 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002186
2187 Here, we didn't need to use a tearDown function because we
2188 modified the test globals, which are a copy of the
2189 sample_doctest module dictionary. The test globals are
2190 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002191 """
2192
2193def test_DocFileSuite():
2194 """We can test tests found in text files using a DocFileSuite.
2195
2196 We create a suite by providing the names of one or more text
2197 files that include examples:
2198
2199 >>> import unittest
2200 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002201 ... 'test_doctest2.txt',
2202 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002203 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002204 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002205
2206 The test files are looked for in the directory containing the
2207 calling module. A package keyword argument can be provided to
2208 specify a different relative location.
2209
2210 >>> import unittest
2211 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2212 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002213 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002214 ... package='test')
2215 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002216 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002217
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002218 Support for using a package's __loader__.get_data() is also
2219 provided.
2220
2221 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002222 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002223 >>> if not hasattr(test, '__loader__'):
2224 ... test.__loader__ = pkgutil.get_loader(test)
2225 ... added_loader = True
2226 >>> try:
2227 ... suite = doctest.DocFileSuite('test_doctest.txt',
2228 ... 'test_doctest2.txt',
2229 ... 'test_doctest4.txt',
2230 ... package='test')
2231 ... suite.run(unittest.TestResult())
2232 ... finally:
2233 ... if added_loader:
2234 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002235 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002236
Edward Loper0273f5b2004-09-18 20:27:04 +00002237 '/' should be used as a path separator. It will be converted
2238 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002239
2240 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2241 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002242 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002243
Edward Loper0273f5b2004-09-18 20:27:04 +00002244 If DocFileSuite is used from an interactive session, then files
2245 are resolved relative to the directory of sys.argv[0]:
2246
Christian Heimes45f9af32007-11-27 21:50:00 +00002247 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002248 >>> save_argv = sys.argv
2249 >>> sys.argv = [test.test_doctest.__file__]
2250 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002251 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002252 >>> sys.argv = save_argv
2253
Edward Loper052d0cd2004-09-19 17:19:33 +00002254 By setting `module_relative=False`, os-specific paths may be
2255 used (including absolute paths and paths relative to the
2256 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002257
2258 >>> # Get the absolute path of the test package.
2259 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2260 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2261
2262 >>> # Use it to find the absolute path of test_doctest.txt.
2263 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2264
Edward Loper052d0cd2004-09-19 17:19:33 +00002265 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002266 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002267 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002268
Edward Loper052d0cd2004-09-19 17:19:33 +00002269 It is an error to specify `package` when `module_relative=False`:
2270
2271 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2272 ... package='test')
2273 Traceback (most recent call last):
2274 ValueError: Package may only be specified for module-relative paths.
2275
Tim Peters19397e52004-08-06 22:02:59 +00002276 You can specify initial global variables:
2277
2278 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2279 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002280 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002281 ... globs={'favorite_color': 'blue'})
2282 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002283 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002284
2285 In this case, we supplied a missing favorite color. You can
2286 provide doctest options:
2287
2288 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2289 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002290 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002291 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2292 ... globs={'favorite_color': 'blue'})
2293 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002294 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002295
2296 And, you can provide setUp and tearDown functions:
2297
Jim Fultonf54bad42004-08-28 14:57:56 +00002298 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002299 ... import test.test_doctest
2300 ... test.test_doctest.sillySetup = True
2301
Jim Fultonf54bad42004-08-28 14:57:56 +00002302 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002303 ... import test.test_doctest
2304 ... del test.test_doctest.sillySetup
2305
2306 Here, we installed a silly variable that the test expects:
2307
2308 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2309 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002310 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002311 ... setUp=setUp, tearDown=tearDown)
2312 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002313 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002314
2315 But the tearDown restores sanity:
2316
2317 >>> import test.test_doctest
2318 >>> test.test_doctest.sillySetup
2319 Traceback (most recent call last):
2320 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002321 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002322
Berker Peksag4882cac2015-04-14 09:30:01 +03002323 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002324 Here, we'll use a setUp function to set the favorite color in
2325 test_doctest.txt:
2326
2327 >>> def setUp(test):
2328 ... test.globs['favorite_color'] = 'blue'
2329
2330 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2331 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002332 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002333
2334 Here, we didn't need to use a tearDown function because we
2335 modified the test globals. The test globals are
2336 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002337
Fred Drake7c404a42004-12-21 23:46:34 +00002338 Tests in a file run using `DocFileSuite` can also access the
2339 `__file__` global, which is set to the name of the file
2340 containing the tests:
2341
2342 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2343 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002344 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002345
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002346 If the tests contain non-ASCII characters, we have to specify which
2347 encoding the file is encoded with. We do so by using the `encoding`
2348 parameter:
2349
2350 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2351 ... 'test_doctest2.txt',
2352 ... 'test_doctest4.txt',
2353 ... encoding='utf-8')
2354 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002355 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002356
Jim Fultonf54bad42004-08-28 14:57:56 +00002357 """
Tim Peters19397e52004-08-06 22:02:59 +00002358
Jim Fulton07a349c2004-08-22 14:10:00 +00002359def test_trailing_space_in_test():
2360 """
Tim Petersa7def722004-08-23 22:13:22 +00002361 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002362
Jim Fulton07a349c2004-08-22 14:10:00 +00002363 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002364 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002365 foo \n
2366 """
Tim Peters19397e52004-08-06 22:02:59 +00002367
Yury Selivanovb532df62014-12-08 15:00:05 -05002368class Wrapper:
2369 def __init__(self, func):
2370 self.func = func
2371 functools.update_wrapper(self, func)
2372
2373 def __call__(self, *args, **kwargs):
2374 self.func(*args, **kwargs)
2375
2376@Wrapper
2377def test_look_in_unwrapped():
2378 """
2379 Docstrings in wrapped functions must be detected as well.
2380
2381 >>> 'one other test'
2382 'one other test'
2383 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002384
2385def test_unittest_reportflags():
2386 """Default unittest reporting flags can be set to control reporting
2387
2388 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2389 only the first failure of each test. First, we'll look at the
2390 output without the flag. The file test_doctest.txt file has two
2391 tests. They both fail if blank lines are disabled:
2392
2393 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2394 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2395 >>> import unittest
2396 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002397 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002398 Traceback ...
2399 Failed example:
2400 favorite_color
2401 ...
2402 Failed example:
2403 if 1:
2404 ...
2405
2406 Note that we see both failures displayed.
2407
2408 >>> old = doctest.set_unittest_reportflags(
2409 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2410
2411 Now, when we run the test:
2412
2413 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002414 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002415 Traceback ...
2416 Failed example:
2417 favorite_color
2418 Exception raised:
2419 ...
2420 NameError: name 'favorite_color' is not defined
2421 <BLANKLINE>
2422 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002423
Jim Fultonf54bad42004-08-28 14:57:56 +00002424 We get only the first failure.
2425
2426 If we give any reporting options when we set up the tests,
2427 however:
2428
2429 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2430 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2431
2432 Then the default eporting options are ignored:
2433
2434 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002435 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002436 Traceback ...
2437 Failed example:
2438 favorite_color
2439 ...
2440 Failed example:
2441 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002442 print('a')
2443 print()
2444 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002445 Differences (ndiff with -expected +actual):
2446 a
2447 - <BLANKLINE>
2448 +
2449 b
2450 <BLANKLINE>
2451 <BLANKLINE>
2452
2453
2454 Test runners can restore the formatting flags after they run:
2455
2456 >>> ignored = doctest.set_unittest_reportflags(old)
2457
2458 """
2459
Edward Loper052d0cd2004-09-19 17:19:33 +00002460def test_testfile(): r"""
2461Tests for the `testfile()` function. This function runs all the
2462doctest examples in a given file. In its simple invokation, it is
2463called with the name of a file, which is taken to be relative to the
2464calling module. The return value is (#failures, #tests).
2465
Florent Xicluna59250852010-02-27 14:21:57 +00002466We don't want `-v` in sys.argv for these tests.
2467
2468 >>> save_argv = sys.argv
2469 >>> if '-v' in sys.argv:
2470 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2471
2472
Edward Loper052d0cd2004-09-19 17:19:33 +00002473 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2474 **********************************************************************
2475 File "...", line 6, in test_doctest.txt
2476 Failed example:
2477 favorite_color
2478 Exception raised:
2479 ...
2480 NameError: name 'favorite_color' is not defined
2481 **********************************************************************
2482 1 items had failures:
2483 1 of 2 in test_doctest.txt
2484 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002485 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002486 >>> doctest.master = None # Reset master.
2487
2488(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002489`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002490same name.)
2491
2492Globals may be specified with the `globs` and `extraglobs` parameters:
2493
2494 >>> globs = {'favorite_color': 'blue'}
2495 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002496 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002497 >>> doctest.master = None # Reset master.
2498
2499 >>> extraglobs = {'favorite_color': 'red'}
2500 >>> doctest.testfile('test_doctest.txt', globs=globs,
2501 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2502 **********************************************************************
2503 File "...", line 6, in test_doctest.txt
2504 Failed example:
2505 favorite_color
2506 Expected:
2507 'blue'
2508 Got:
2509 'red'
2510 **********************************************************************
2511 1 items had failures:
2512 1 of 2 in test_doctest.txt
2513 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002514 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002515 >>> doctest.master = None # Reset master.
2516
2517The file may be made relative to a given module or package, using the
2518optional `module_relative` parameter:
2519
2520 >>> doctest.testfile('test_doctest.txt', globs=globs,
2521 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002522 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002523 >>> doctest.master = None # Reset master.
2524
Ezio Melotti13925002011-03-16 11:05:33 +02002525Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002526
2527 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2528 Trying:
2529 favorite_color
2530 Expecting:
2531 'blue'
2532 ok
2533 Trying:
2534 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002535 print('a')
2536 print()
2537 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002538 Expecting:
2539 a
2540 <BLANKLINE>
2541 b
2542 ok
2543 1 items passed all tests:
2544 2 tests in test_doctest.txt
2545 2 tests in 1 items.
2546 2 passed and 0 failed.
2547 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002548 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002549 >>> doctest.master = None # Reset master.
2550
2551The name of the test may be specified with the optional `name`
2552parameter:
2553
2554 >>> doctest.testfile('test_doctest.txt', name='newname')
2555 ... # doctest: +ELLIPSIS
2556 **********************************************************************
2557 File "...", line 6, in newname
2558 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002559 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002560 >>> doctest.master = None # Reset master.
2561
Ezio Melotti13925002011-03-16 11:05:33 +02002562The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002563parameter:
2564
2565 >>> doctest.testfile('test_doctest.txt', report=False)
2566 ... # doctest: +ELLIPSIS
2567 **********************************************************************
2568 File "...", line 6, in test_doctest.txt
2569 Failed example:
2570 favorite_color
2571 Exception raised:
2572 ...
2573 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002574 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002575 >>> doctest.master = None # Reset master.
2576
2577The optional keyword argument `raise_on_error` can be used to raise an
2578exception on the first error (which may be useful for postmortem
2579debugging):
2580
2581 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2582 ... # doctest: +ELLIPSIS
2583 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002584 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002585 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002586
2587If the tests contain non-ASCII characters, the tests might fail, since
2588it's unknown which encoding is used. The encoding can be specified
2589using the optional keyword argument `encoding`:
2590
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002591 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002592 **********************************************************************
2593 File "...", line 7, in test_doctest4.txt
2594 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002595 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002596 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002597 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002598 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002599 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002600 **********************************************************************
2601 ...
2602 **********************************************************************
2603 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002604 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002605 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002606 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002607 >>> doctest.master = None # Reset master.
2608
2609 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002610 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002611 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002612
2613Test the verbose output:
2614
2615 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2616 Trying:
2617 'föö'
2618 Expecting:
2619 'f\xf6\xf6'
2620 ok
2621 Trying:
2622 'bÄ…r'
2623 Expecting:
2624 'b\u0105r'
2625 ok
2626 1 items passed all tests:
2627 2 tests in test_doctest4.txt
2628 2 tests in 1 items.
2629 2 passed and 0 failed.
2630 Test passed.
2631 TestResults(failed=0, attempted=2)
2632 >>> doctest.master = None # Reset master.
2633 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002634"""
2635
R David Murrayb48cb292014-10-02 22:42:42 -04002636def test_lineendings(): r"""
2637*nix systems use \n line endings, while Windows systems use \r\n. Python
2638handles this using universal newline mode for reading files. Let's make
2639sure doctest does so (issue 8473) by creating temporary test files using each
2640of the two line disciplines. One of the two will be the "wrong" one for the
2641platform the test is run on.
2642
2643Windows line endings first:
2644
2645 >>> import tempfile, os
2646 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002647 >>> with open(fn, 'wb') as f:
2648 ... f.write(b'Test:\r\n\r\n >>> x = 1 + 1\r\n\r\nDone.\r\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002649 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002650 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002651 TestResults(failed=0, attempted=1)
2652 >>> os.remove(fn)
2653
2654And now *nix line endings:
2655
2656 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002657 >>> with open(fn, 'wb') as f:
2658 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002659 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002660 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002661 TestResults(failed=0, attempted=1)
2662 >>> os.remove(fn)
2663
2664"""
2665
R. David Murray58641de2009-06-12 15:33:19 +00002666def test_testmod(): r"""
2667Tests for the testmod function. More might be useful, but for now we're just
2668testing the case raised by Issue 6195, where trying to doctest a C module would
2669fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2670out of the binary module.
2671
2672 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002673 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002674 TestResults(failed=0, attempted=0)
2675"""
2676
Victor Stinner9d396392010-10-16 21:54:59 +00002677try:
2678 os.fsencode("foo-bär@baz.py")
2679except UnicodeEncodeError:
2680 # Skip the test: the filesystem encoding is unable to encode the filename
2681 pass
2682else:
2683 def test_unicode(): """
2684Check doctest with a non-ascii filename:
2685
2686 >>> doc = '''
2687 ... >>> raise Exception('clé')
2688 ... '''
2689 ...
2690 >>> parser = doctest.DocTestParser()
2691 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2692 >>> test
2693 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2694 >>> runner = doctest.DocTestRunner(verbose=False)
2695 >>> runner.run(test) # doctest: +ELLIPSIS
2696 **********************************************************************
2697 File "foo-bär@baz.py", line 2, in foo-bär@baz
2698 Failed example:
2699 raise Exception('clé')
2700 Exception raised:
2701 Traceback (most recent call last):
2702 File ...
2703 compileflags, 1), test.globs)
2704 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2705 raise Exception('clé')
2706 Exception: clé
2707 TestResults(failed=1, attempted=1)
2708 """
2709
R David Murray5707d502013-06-23 14:24:13 -04002710def test_CLI(): r"""
2711The doctest module can be used to run doctests against an arbitrary file.
2712These tests test this CLI functionality.
2713
2714We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002715to a temp dir to run the command against. Due to a current limitation in
2716script_helpers, though, we need a little utility function to turn the returned
2717output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002718
R David Murray4af68982013-06-25 08:11:22 -04002719 >>> def normalize(s):
2720 ... return '\n'.join(s.decode().splitlines())
2721
R David Murray4af68982013-06-25 08:11:22 -04002722With those preliminaries out of the way, we'll start with a file with two
2723simple tests and no errors. We'll run both the unadorned doctest command, and
2724the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002725
Berker Peksagce643912015-05-06 06:33:17 +03002726 >>> from test.support import script_helper, temp_dir
2727 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002728 ... fn = os.path.join(tmpdir, 'myfile.doc')
2729 ... with open(fn, 'w') as f:
2730 ... _ = f.write('This is a very simple test file.\n')
2731 ... _ = f.write(' >>> 1 + 1\n')
2732 ... _ = f.write(' 2\n')
2733 ... _ = f.write(' >>> "a"\n')
2734 ... _ = f.write(" 'a'\n")
2735 ... _ = f.write('\n')
2736 ... _ = f.write('And that is it.\n')
2737 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002738 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002739 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002740 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002741
2742With no arguments and passing tests, we should get no output:
2743
2744 >>> rc1, out1, err1
2745 (0, b'', b'')
2746
2747With the verbose flag, we should see the test output, but no error output:
2748
2749 >>> rc2, err2
2750 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002751 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002752 Trying:
2753 1 + 1
2754 Expecting:
2755 2
2756 ok
2757 Trying:
2758 "a"
2759 Expecting:
2760 'a'
2761 ok
2762 1 items passed all tests:
2763 2 tests in myfile.doc
2764 2 tests in 1 items.
2765 2 passed and 0 failed.
2766 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002767
2768Now we'll write a couple files, one with three tests, the other a python module
2769with two tests, both of the files having "errors" in the tests that can be made
2770non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2771the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002772allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002773ability to process more than one file on the command line and, since the second
2774file ends in '.py', its handling of python module files (as opposed to straight
2775text files).
2776
Berker Peksagce643912015-05-06 06:33:17 +03002777 >>> from test.support import script_helper, temp_dir
2778 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002779 ... fn = os.path.join(tmpdir, 'myfile.doc')
2780 ... with open(fn, 'w') as f:
2781 ... _ = f.write('This is another simple test file.\n')
2782 ... _ = f.write(' >>> 1 + 1\n')
2783 ... _ = f.write(' 2\n')
2784 ... _ = f.write(' >>> "abcdef"\n')
2785 ... _ = f.write(" 'a...f'\n")
2786 ... _ = f.write(' >>> "ajkml"\n')
2787 ... _ = f.write(" 'a...l'\n")
2788 ... _ = f.write('\n')
2789 ... _ = f.write('And that is it.\n')
2790 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2791 ... with open(fn2, 'w') as f:
2792 ... _ = f.write('def test_func():\n')
2793 ... _ = f.write(' \"\"\"\n')
2794 ... _ = f.write(' This is simple python test function.\n')
2795 ... _ = f.write(' >>> 1 + 1\n')
2796 ... _ = f.write(' 2\n')
2797 ... _ = f.write(' >>> "abc def"\n')
2798 ... _ = f.write(" 'abc def'\n")
2799 ... _ = f.write("\n")
2800 ... _ = f.write(' \"\"\"\n')
2801 ... import shutil
2802 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002803 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002804 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002805 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002806 ... rc3, out3, err3 = script_helper.assert_python_ok(
2807 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002808 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002809 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002810 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002811 ... rc5, out5, err5 = script_helper.assert_python_ok(
2812 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002813 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002814
2815Our first test run will show the errors from the first file (doctest stops if a
2816file has errors). Note that doctest test-run error output appears on stdout,
2817not stderr:
2818
2819 >>> rc1, err1
2820 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002821 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002822 **********************************************************************
2823 File "...myfile.doc", line 4, in myfile.doc
2824 Failed example:
2825 "abcdef"
2826 Expected:
2827 'a...f'
2828 Got:
2829 'abcdef'
2830 **********************************************************************
2831 File "...myfile.doc", line 6, in myfile.doc
2832 Failed example:
2833 "ajkml"
2834 Expected:
2835 'a...l'
2836 Got:
2837 'ajkml'
2838 **********************************************************************
2839 1 items had failures:
2840 2 of 3 in myfile.doc
2841 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002842
2843With -o ELLIPSIS specified, the second run, against just the first file, should
2844produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2845should the third, which ran against both files:
2846
2847 >>> rc2, out2, err2
2848 (0, b'', b'')
2849 >>> rc3, out3, err3
2850 (0, b'', b'')
2851
2852The fourth run uses FAIL_FAST, so we should see only one error:
2853
2854 >>> rc4, err4
2855 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002856 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002857 **********************************************************************
2858 File "...myfile.doc", line 4, in myfile.doc
2859 Failed example:
2860 "abcdef"
2861 Expected:
2862 'a...f'
2863 Got:
2864 'abcdef'
2865 **********************************************************************
2866 1 items had failures:
2867 1 of 2 in myfile.doc
2868 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002869
2870The fifth test uses verbose with the two options, so we should get verbose
2871success output for the tests in both files:
2872
2873 >>> rc5, err5
2874 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002875 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002876 Trying:
2877 1 + 1
2878 Expecting:
2879 2
2880 ok
2881 Trying:
2882 "abcdef"
2883 Expecting:
2884 'a...f'
2885 ok
2886 Trying:
2887 "ajkml"
2888 Expecting:
2889 'a...l'
2890 ok
2891 1 items passed all tests:
2892 3 tests in myfile.doc
2893 3 tests in 1 items.
2894 3 passed and 0 failed.
2895 Test passed.
2896 Trying:
2897 1 + 1
2898 Expecting:
2899 2
2900 ok
2901 Trying:
2902 "abc def"
2903 Expecting:
2904 'abc def'
2905 ok
2906 1 items had no tests:
2907 myfile2
2908 1 items passed all tests:
2909 2 tests in myfile2.test_func
2910 2 tests in 2 items.
2911 2 passed and 0 failed.
2912 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002913
2914We should also check some typical error cases.
2915
2916Invalid file name:
2917
2918 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002919 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04002920 >>> rc, out
2921 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002922 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002923 Traceback (most recent call last):
2924 ...
2925 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
2926
2927Invalid doctest option:
2928
2929 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002930 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04002931 >>> rc, out
2932 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04002933 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002934 usage...invalid...nosuchoption...
2935
2936"""
2937
Tim Peters8485b562004-08-04 18:46:34 +00002938######################################################################
2939## Main
2940######################################################################
2941
2942def test_main():
2943 # Check the doctest cases in doctest itself:
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02002944 ret = support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002945 # Check the doctest cases defined here:
2946 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002947 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002948
Victor Stinner45df8202010-04-28 22:31:17 +00002949import sys, re, io
2950
Tim Peters8485b562004-08-04 18:46:34 +00002951def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002952 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01002953 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00002954 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002955 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002956 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002957 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002958 r.write_results(show_missing=True, summary=True,
2959 coverdir=coverdir)
2960
2961if __name__ == '__main__':
2962 if '-c' in sys.argv:
2963 test_coverage('/tmp/doctest.cover')
2964 else:
2965 test_main()