blob: 2258c6b1baed26bd930bc0bfd202838001a7d1d3 [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 ...
R David Murray44b548d2016-09-08 13:59:53 -0400294 ... >>> 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 >>> real_stdin = sys.stdin
1880 >>> sys.stdin = _FakeInput([
1881 ... 'print(x)', # print data defined by the example
1882 ... 'continue', # stop debugging
1883 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001884
Brett Cannon31f59292011-02-21 19:29:56 +00001885 >>> try: runner.run(test)
1886 ... finally: sys.stdin = real_stdin
1887 --Return--
1888 > <doctest foo-bar@baz[2]>(1)<module>()->None
1889 -> import pdb; pdb.set_trace()
1890 (Pdb) print(x)
1891 42
1892 (Pdb) continue
1893 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001894
Brett Cannon31f59292011-02-21 19:29:56 +00001895 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001896
Brett Cannon31f59292011-02-21 19:29:56 +00001897 >>> def calls_set_trace():
1898 ... y=2
1899 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001900
Brett Cannon31f59292011-02-21 19:29:56 +00001901 >>> doc = '''
1902 ... >>> x=1
1903 ... >>> calls_set_trace()
1904 ... '''
1905 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1906 >>> real_stdin = sys.stdin
1907 >>> sys.stdin = _FakeInput([
1908 ... 'print(y)', # print data defined in the function
1909 ... 'up', # out of function
1910 ... 'print(x)', # print data defined by the example
1911 ... 'continue', # stop debugging
1912 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001913
Brett Cannon31f59292011-02-21 19:29:56 +00001914 >>> try:
1915 ... runner.run(test)
1916 ... finally:
1917 ... sys.stdin = real_stdin
1918 --Return--
Serhiy Storchakae437a102016-04-24 21:41:02 +03001919 > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
Brett Cannon31f59292011-02-21 19:29:56 +00001920 -> import pdb; pdb.set_trace()
1921 (Pdb) print(y)
1922 2
1923 (Pdb) up
1924 > <doctest foo-bar@baz[1]>(1)<module>()
1925 -> calls_set_trace()
1926 (Pdb) print(x)
1927 1
1928 (Pdb) continue
1929 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001930
Brett Cannon31f59292011-02-21 19:29:56 +00001931 During interactive debugging, source code is shown, even for
1932 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001933
Brett Cannon31f59292011-02-21 19:29:56 +00001934 >>> doc = '''
1935 ... >>> def f(x):
1936 ... ... g(x*2)
1937 ... >>> def g(x):
1938 ... ... print(x+3)
1939 ... ... import pdb; pdb.set_trace()
1940 ... >>> f(3)
1941 ... '''
1942 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1943 >>> real_stdin = sys.stdin
1944 >>> sys.stdin = _FakeInput([
1945 ... 'list', # list source from example 2
1946 ... 'next', # return from g()
1947 ... 'list', # list source from example 1
1948 ... 'next', # return from f()
1949 ... 'list', # list source from example 3
1950 ... 'continue', # stop debugging
1951 ... ''])
1952 >>> try: runner.run(test)
1953 ... finally: sys.stdin = real_stdin
1954 ... # doctest: +NORMALIZE_WHITESPACE
1955 --Return--
1956 > <doctest foo-bar@baz[1]>(3)g()->None
1957 -> import pdb; pdb.set_trace()
1958 (Pdb) list
1959 1 def g(x):
1960 2 print(x+3)
1961 3 -> import pdb; pdb.set_trace()
1962 [EOF]
1963 (Pdb) next
1964 --Return--
1965 > <doctest foo-bar@baz[0]>(2)f()->None
1966 -> g(x*2)
1967 (Pdb) list
1968 1 def f(x):
1969 2 -> g(x*2)
1970 [EOF]
1971 (Pdb) next
1972 --Return--
1973 > <doctest foo-bar@baz[2]>(1)<module>()->None
1974 -> f(3)
1975 (Pdb) list
1976 1 -> f(3)
1977 [EOF]
1978 (Pdb) continue
1979 **********************************************************************
1980 File "foo-bar@baz.py", line 7, in foo-bar@baz
1981 Failed example:
1982 f(3)
1983 Expected nothing
1984 Got:
1985 9
1986 TestResults(failed=1, attempted=3)
1987 """
Jim Fulton356fd192004-08-09 11:34:47 +00001988
Brett Cannon31f59292011-02-21 19:29:56 +00001989 def test_pdb_set_trace_nested():
1990 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00001991
Brett Cannon31f59292011-02-21 19:29:56 +00001992 >>> class C(object):
1993 ... def calls_set_trace(self):
1994 ... y = 1
1995 ... import pdb; pdb.set_trace()
1996 ... self.f1()
1997 ... y = 2
1998 ... def f1(self):
1999 ... x = 1
2000 ... self.f2()
2001 ... x = 2
2002 ... def f2(self):
2003 ... z = 1
2004 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002005
Brett Cannon31f59292011-02-21 19:29:56 +00002006 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002007
Brett Cannon31f59292011-02-21 19:29:56 +00002008 >>> doc = '''
2009 ... >>> a = 1
2010 ... >>> calls_set_trace()
2011 ... '''
2012 >>> parser = doctest.DocTestParser()
2013 >>> runner = doctest.DocTestRunner(verbose=False)
2014 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2015 >>> real_stdin = sys.stdin
2016 >>> sys.stdin = _FakeInput([
2017 ... 'print(y)', # print data defined in the function
2018 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2019 ... 'up', 'print(x)',
2020 ... 'up', 'print(y)',
2021 ... 'up', 'print(foo)',
2022 ... 'continue', # stop debugging
2023 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002024
Brett Cannon31f59292011-02-21 19:29:56 +00002025 >>> try:
2026 ... runner.run(test)
2027 ... finally:
2028 ... sys.stdin = real_stdin
2029 ... # doctest: +REPORT_NDIFF
2030 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2031 -> self.f1()
2032 (Pdb) print(y)
2033 1
2034 (Pdb) step
2035 --Call--
2036 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2037 -> def f1(self):
2038 (Pdb) step
2039 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2040 -> x = 1
2041 (Pdb) step
2042 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2043 -> self.f2()
2044 (Pdb) step
2045 --Call--
2046 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2047 -> def f2(self):
2048 (Pdb) step
2049 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2050 -> z = 1
2051 (Pdb) step
2052 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2053 -> z = 2
2054 (Pdb) print(z)
2055 1
2056 (Pdb) up
2057 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2058 -> self.f2()
2059 (Pdb) print(x)
2060 1
2061 (Pdb) up
2062 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2063 -> self.f1()
2064 (Pdb) print(y)
2065 1
2066 (Pdb) up
2067 > <doctest foo-bar@baz[1]>(1)<module>()
2068 -> calls_set_trace()
2069 (Pdb) print(foo)
2070 *** NameError: name 'foo' is not defined
2071 (Pdb) continue
2072 TestResults(failed=0, attempted=2)
2073 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002074
Tim Peters19397e52004-08-06 22:02:59 +00002075def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002076 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002077
2078 We create a Suite by providing a module. A module can be provided
2079 by passing a module object:
2080
2081 >>> import unittest
2082 >>> import test.sample_doctest
2083 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2084 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002085 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002086
2087 We can also supply the module by name:
2088
2089 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2090 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002091 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002092
R David Murray5abd76a2012-09-10 10:15:58 -04002093 The module need not contain any doctest examples:
2094
2095 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2096 >>> suite.run(unittest.TestResult())
2097 <unittest.result.TestResult run=0 errors=0 failures=0>
2098
R David Murray1976d9b2014-04-14 20:28:36 -04002099 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002100
R David Murray1976d9b2014-04-14 20:28:36 -04002101 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002102 >>> suite.run(unittest.TestResult())
2103 <unittest.result.TestResult run=0 errors=0 failures=0>
2104
Tim Peters19397e52004-08-06 22:02:59 +00002105 We can use the current module:
2106
2107 >>> suite = test.sample_doctest.test_suite()
2108 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002109 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002110
R David Murray1976d9b2014-04-14 20:28:36 -04002111 We can also provide a DocTestFinder:
2112
2113 >>> finder = doctest.DocTestFinder()
2114 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2115 ... test_finder=finder)
2116 >>> suite.run(unittest.TestResult())
2117 <unittest.result.TestResult run=9 errors=0 failures=4>
2118
2119 The DocTestFinder need not return any tests:
2120
2121 >>> finder = doctest.DocTestFinder()
2122 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2123 ... test_finder=finder)
2124 >>> suite.run(unittest.TestResult())
2125 <unittest.result.TestResult run=0 errors=0 failures=0>
2126
Tim Peters19397e52004-08-06 22:02:59 +00002127 We can supply global variables. If we pass globs, they will be
2128 used instead of the module globals. Here we'll pass an empty
2129 globals, triggering an extra error:
2130
2131 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2132 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002133 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002134
2135 Alternatively, we can provide extra globals. Here we'll make an
2136 error go away by providing an extra global variable:
2137
2138 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2139 ... extraglobs={'y': 1})
2140 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002141 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002142
2143 You can pass option flags. Here we'll cause an extra error
2144 by disabling the blank-line feature:
2145
2146 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002147 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002148 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002149 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002150
Tim Peters1e277ee2004-08-07 05:37:52 +00002151 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002152
Jim Fultonf54bad42004-08-28 14:57:56 +00002153 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002154 ... import test.test_doctest
2155 ... test.test_doctest.sillySetup = True
2156
Jim Fultonf54bad42004-08-28 14:57:56 +00002157 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002158 ... import test.test_doctest
2159 ... del test.test_doctest.sillySetup
2160
2161 Here, we installed a silly variable that the test expects:
2162
2163 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2164 ... setUp=setUp, tearDown=tearDown)
2165 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002166 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002167
2168 But the tearDown restores sanity:
2169
2170 >>> import test.test_doctest
2171 >>> test.test_doctest.sillySetup
2172 Traceback (most recent call last):
2173 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002174 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002175
Berker Peksag4882cac2015-04-14 09:30:01 +03002176 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002177 we'll use the setUp function to supply the missing variable y:
2178
2179 >>> def setUp(test):
2180 ... test.globs['y'] = 1
2181
2182 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2183 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002184 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002185
2186 Here, we didn't need to use a tearDown function because we
2187 modified the test globals, which are a copy of the
2188 sample_doctest module dictionary. The test globals are
2189 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002190 """
2191
2192def test_DocFileSuite():
2193 """We can test tests found in text files using a DocFileSuite.
2194
2195 We create a suite by providing the names of one or more text
2196 files that include examples:
2197
2198 >>> import unittest
2199 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002200 ... 'test_doctest2.txt',
2201 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002202 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002203 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002204
2205 The test files are looked for in the directory containing the
2206 calling module. A package keyword argument can be provided to
2207 specify a different relative location.
2208
2209 >>> import unittest
2210 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2211 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002212 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002213 ... package='test')
2214 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002215 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002216
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002217 Support for using a package's __loader__.get_data() is also
2218 provided.
2219
2220 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002221 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002222 >>> if not hasattr(test, '__loader__'):
2223 ... test.__loader__ = pkgutil.get_loader(test)
2224 ... added_loader = True
2225 >>> try:
2226 ... suite = doctest.DocFileSuite('test_doctest.txt',
2227 ... 'test_doctest2.txt',
2228 ... 'test_doctest4.txt',
2229 ... package='test')
2230 ... suite.run(unittest.TestResult())
2231 ... finally:
2232 ... if added_loader:
2233 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002234 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002235
Edward Loper0273f5b2004-09-18 20:27:04 +00002236 '/' should be used as a path separator. It will be converted
2237 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002238
2239 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2240 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002241 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002242
Edward Loper0273f5b2004-09-18 20:27:04 +00002243 If DocFileSuite is used from an interactive session, then files
2244 are resolved relative to the directory of sys.argv[0]:
2245
Christian Heimes45f9af32007-11-27 21:50:00 +00002246 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002247 >>> save_argv = sys.argv
2248 >>> sys.argv = [test.test_doctest.__file__]
2249 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002250 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002251 >>> sys.argv = save_argv
2252
Edward Loper052d0cd2004-09-19 17:19:33 +00002253 By setting `module_relative=False`, os-specific paths may be
2254 used (including absolute paths and paths relative to the
2255 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002256
2257 >>> # Get the absolute path of the test package.
2258 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2259 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2260
2261 >>> # Use it to find the absolute path of test_doctest.txt.
2262 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2263
Edward Loper052d0cd2004-09-19 17:19:33 +00002264 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002265 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002266 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002267
Edward Loper052d0cd2004-09-19 17:19:33 +00002268 It is an error to specify `package` when `module_relative=False`:
2269
2270 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2271 ... package='test')
2272 Traceback (most recent call last):
2273 ValueError: Package may only be specified for module-relative paths.
2274
Tim Peters19397e52004-08-06 22:02:59 +00002275 You can specify initial global variables:
2276
2277 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2278 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002279 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002280 ... globs={'favorite_color': 'blue'})
2281 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002282 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002283
2284 In this case, we supplied a missing favorite color. You can
2285 provide doctest options:
2286
2287 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2288 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002289 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002290 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2291 ... globs={'favorite_color': 'blue'})
2292 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002293 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002294
2295 And, you can provide setUp and tearDown functions:
2296
Jim Fultonf54bad42004-08-28 14:57:56 +00002297 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002298 ... import test.test_doctest
2299 ... test.test_doctest.sillySetup = True
2300
Jim Fultonf54bad42004-08-28 14:57:56 +00002301 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002302 ... import test.test_doctest
2303 ... del test.test_doctest.sillySetup
2304
2305 Here, we installed a silly variable that the test expects:
2306
2307 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2308 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002309 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002310 ... setUp=setUp, tearDown=tearDown)
2311 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002312 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002313
2314 But the tearDown restores sanity:
2315
2316 >>> import test.test_doctest
2317 >>> test.test_doctest.sillySetup
2318 Traceback (most recent call last):
2319 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002320 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002321
Berker Peksag4882cac2015-04-14 09:30:01 +03002322 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002323 Here, we'll use a setUp function to set the favorite color in
2324 test_doctest.txt:
2325
2326 >>> def setUp(test):
2327 ... test.globs['favorite_color'] = 'blue'
2328
2329 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2330 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002331 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002332
2333 Here, we didn't need to use a tearDown function because we
2334 modified the test globals. The test globals are
2335 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002336
Fred Drake7c404a42004-12-21 23:46:34 +00002337 Tests in a file run using `DocFileSuite` can also access the
2338 `__file__` global, which is set to the name of the file
2339 containing the tests:
2340
Benjamin Petersonab078e92016-07-13 21:13:29 -07002341 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
Fred Drake7c404a42004-12-21 23:46:34 +00002342 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002343 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002344
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002345 If the tests contain non-ASCII characters, we have to specify which
2346 encoding the file is encoded with. We do so by using the `encoding`
2347 parameter:
2348
2349 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2350 ... 'test_doctest2.txt',
2351 ... 'test_doctest4.txt',
2352 ... encoding='utf-8')
2353 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002354 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002355
Jim Fultonf54bad42004-08-28 14:57:56 +00002356 """
Tim Peters19397e52004-08-06 22:02:59 +00002357
Jim Fulton07a349c2004-08-22 14:10:00 +00002358def test_trailing_space_in_test():
2359 """
Tim Petersa7def722004-08-23 22:13:22 +00002360 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002361
Jim Fulton07a349c2004-08-22 14:10:00 +00002362 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002363 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002364 foo \n
2365 """
Tim Peters19397e52004-08-06 22:02:59 +00002366
Yury Selivanovb532df62014-12-08 15:00:05 -05002367class Wrapper:
2368 def __init__(self, func):
2369 self.func = func
2370 functools.update_wrapper(self, func)
2371
2372 def __call__(self, *args, **kwargs):
2373 self.func(*args, **kwargs)
2374
2375@Wrapper
2376def test_look_in_unwrapped():
2377 """
2378 Docstrings in wrapped functions must be detected as well.
2379
2380 >>> 'one other test'
2381 'one other test'
2382 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002383
2384def test_unittest_reportflags():
2385 """Default unittest reporting flags can be set to control reporting
2386
2387 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2388 only the first failure of each test. First, we'll look at the
2389 output without the flag. The file test_doctest.txt file has two
2390 tests. They both fail if blank lines are disabled:
2391
2392 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2393 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2394 >>> import unittest
2395 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002396 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002397 Traceback ...
2398 Failed example:
2399 favorite_color
2400 ...
2401 Failed example:
2402 if 1:
2403 ...
2404
2405 Note that we see both failures displayed.
2406
2407 >>> old = doctest.set_unittest_reportflags(
2408 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2409
2410 Now, when we run the test:
2411
2412 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002413 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002414 Traceback ...
2415 Failed example:
2416 favorite_color
2417 Exception raised:
2418 ...
2419 NameError: name 'favorite_color' is not defined
2420 <BLANKLINE>
2421 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002422
Jim Fultonf54bad42004-08-28 14:57:56 +00002423 We get only the first failure.
2424
2425 If we give any reporting options when we set up the tests,
2426 however:
2427
2428 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2429 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2430
2431 Then the default eporting options are ignored:
2432
2433 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002434 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002435 Traceback ...
2436 Failed example:
2437 favorite_color
2438 ...
2439 Failed example:
2440 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002441 print('a')
2442 print()
2443 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002444 Differences (ndiff with -expected +actual):
2445 a
2446 - <BLANKLINE>
2447 +
2448 b
2449 <BLANKLINE>
2450 <BLANKLINE>
2451
2452
2453 Test runners can restore the formatting flags after they run:
2454
2455 >>> ignored = doctest.set_unittest_reportflags(old)
2456
2457 """
2458
Edward Loper052d0cd2004-09-19 17:19:33 +00002459def test_testfile(): r"""
2460Tests for the `testfile()` function. This function runs all the
2461doctest examples in a given file. In its simple invokation, it is
2462called with the name of a file, which is taken to be relative to the
2463calling module. The return value is (#failures, #tests).
2464
Florent Xicluna59250852010-02-27 14:21:57 +00002465We don't want `-v` in sys.argv for these tests.
2466
2467 >>> save_argv = sys.argv
2468 >>> if '-v' in sys.argv:
2469 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2470
2471
Edward Loper052d0cd2004-09-19 17:19:33 +00002472 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2473 **********************************************************************
2474 File "...", line 6, in test_doctest.txt
2475 Failed example:
2476 favorite_color
2477 Exception raised:
2478 ...
2479 NameError: name 'favorite_color' is not defined
2480 **********************************************************************
2481 1 items had failures:
2482 1 of 2 in test_doctest.txt
2483 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002484 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002485 >>> doctest.master = None # Reset master.
2486
2487(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002488`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002489same name.)
2490
2491Globals may be specified with the `globs` and `extraglobs` parameters:
2492
2493 >>> globs = {'favorite_color': 'blue'}
2494 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002495 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002496 >>> doctest.master = None # Reset master.
2497
2498 >>> extraglobs = {'favorite_color': 'red'}
2499 >>> doctest.testfile('test_doctest.txt', globs=globs,
2500 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2501 **********************************************************************
2502 File "...", line 6, in test_doctest.txt
2503 Failed example:
2504 favorite_color
2505 Expected:
2506 'blue'
2507 Got:
2508 'red'
2509 **********************************************************************
2510 1 items had failures:
2511 1 of 2 in test_doctest.txt
2512 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002513 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002514 >>> doctest.master = None # Reset master.
2515
2516The file may be made relative to a given module or package, using the
2517optional `module_relative` parameter:
2518
2519 >>> doctest.testfile('test_doctest.txt', globs=globs,
2520 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002521 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002522 >>> doctest.master = None # Reset master.
2523
Ezio Melotti13925002011-03-16 11:05:33 +02002524Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002525
2526 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2527 Trying:
2528 favorite_color
2529 Expecting:
2530 'blue'
2531 ok
2532 Trying:
2533 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002534 print('a')
2535 print()
2536 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002537 Expecting:
2538 a
2539 <BLANKLINE>
2540 b
2541 ok
2542 1 items passed all tests:
2543 2 tests in test_doctest.txt
2544 2 tests in 1 items.
2545 2 passed and 0 failed.
2546 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002547 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002548 >>> doctest.master = None # Reset master.
2549
2550The name of the test may be specified with the optional `name`
2551parameter:
2552
2553 >>> doctest.testfile('test_doctest.txt', name='newname')
2554 ... # doctest: +ELLIPSIS
2555 **********************************************************************
2556 File "...", line 6, in newname
2557 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002558 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002559 >>> doctest.master = None # Reset master.
2560
Ezio Melotti13925002011-03-16 11:05:33 +02002561The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002562parameter:
2563
2564 >>> doctest.testfile('test_doctest.txt', report=False)
2565 ... # doctest: +ELLIPSIS
2566 **********************************************************************
2567 File "...", line 6, in test_doctest.txt
2568 Failed example:
2569 favorite_color
2570 Exception raised:
2571 ...
2572 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002573 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002574 >>> doctest.master = None # Reset master.
2575
2576The optional keyword argument `raise_on_error` can be used to raise an
2577exception on the first error (which may be useful for postmortem
2578debugging):
2579
2580 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2581 ... # doctest: +ELLIPSIS
2582 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002583 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002584 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002585
2586If the tests contain non-ASCII characters, the tests might fail, since
2587it's unknown which encoding is used. The encoding can be specified
2588using the optional keyword argument `encoding`:
2589
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002590 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002591 **********************************************************************
2592 File "...", line 7, in test_doctest4.txt
2593 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002594 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002595 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002596 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002597 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002598 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002599 **********************************************************************
2600 ...
2601 **********************************************************************
2602 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002603 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002604 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002605 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002606 >>> doctest.master = None # Reset master.
2607
2608 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002609 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002610 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002611
2612Test the verbose output:
2613
2614 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2615 Trying:
2616 'föö'
2617 Expecting:
2618 'f\xf6\xf6'
2619 ok
2620 Trying:
2621 'bÄ…r'
2622 Expecting:
2623 'b\u0105r'
2624 ok
2625 1 items passed all tests:
2626 2 tests in test_doctest4.txt
2627 2 tests in 1 items.
2628 2 passed and 0 failed.
2629 Test passed.
2630 TestResults(failed=0, attempted=2)
2631 >>> doctest.master = None # Reset master.
2632 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002633"""
2634
R David Murrayb48cb292014-10-02 22:42:42 -04002635def test_lineendings(): r"""
2636*nix systems use \n line endings, while Windows systems use \r\n. Python
2637handles this using universal newline mode for reading files. Let's make
2638sure doctest does so (issue 8473) by creating temporary test files using each
2639of the two line disciplines. One of the two will be the "wrong" one for the
2640platform the test is run on.
2641
2642Windows line endings first:
2643
2644 >>> import tempfile, os
2645 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002646 >>> with open(fn, 'wb') as f:
2647 ... 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 -04002648 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002649 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002650 TestResults(failed=0, attempted=1)
2651 >>> os.remove(fn)
2652
2653And now *nix line endings:
2654
2655 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002656 >>> with open(fn, 'wb') as f:
2657 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002658 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002659 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002660 TestResults(failed=0, attempted=1)
2661 >>> os.remove(fn)
2662
2663"""
2664
R. David Murray58641de2009-06-12 15:33:19 +00002665def test_testmod(): r"""
2666Tests for the testmod function. More might be useful, but for now we're just
2667testing the case raised by Issue 6195, where trying to doctest a C module would
2668fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2669out of the binary module.
2670
2671 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002672 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002673 TestResults(failed=0, attempted=0)
2674"""
2675
Victor Stinner9d396392010-10-16 21:54:59 +00002676try:
2677 os.fsencode("foo-bär@baz.py")
2678except UnicodeEncodeError:
2679 # Skip the test: the filesystem encoding is unable to encode the filename
2680 pass
2681else:
2682 def test_unicode(): """
2683Check doctest with a non-ascii filename:
2684
2685 >>> doc = '''
2686 ... >>> raise Exception('clé')
2687 ... '''
2688 ...
2689 >>> parser = doctest.DocTestParser()
2690 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2691 >>> test
2692 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2693 >>> runner = doctest.DocTestRunner(verbose=False)
2694 >>> runner.run(test) # doctest: +ELLIPSIS
2695 **********************************************************************
2696 File "foo-bär@baz.py", line 2, in foo-bär@baz
2697 Failed example:
2698 raise Exception('clé')
2699 Exception raised:
2700 Traceback (most recent call last):
2701 File ...
2702 compileflags, 1), test.globs)
2703 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2704 raise Exception('clé')
2705 Exception: clé
2706 TestResults(failed=1, attempted=1)
2707 """
2708
R David Murray5707d502013-06-23 14:24:13 -04002709def test_CLI(): r"""
2710The doctest module can be used to run doctests against an arbitrary file.
2711These tests test this CLI functionality.
2712
2713We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002714to a temp dir to run the command against. Due to a current limitation in
2715script_helpers, though, we need a little utility function to turn the returned
2716output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002717
R David Murray4af68982013-06-25 08:11:22 -04002718 >>> def normalize(s):
2719 ... return '\n'.join(s.decode().splitlines())
2720
R David Murray4af68982013-06-25 08:11:22 -04002721With those preliminaries out of the way, we'll start with a file with two
2722simple tests and no errors. We'll run both the unadorned doctest command, and
2723the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002724
Berker Peksagce643912015-05-06 06:33:17 +03002725 >>> from test.support import script_helper, temp_dir
2726 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002727 ... fn = os.path.join(tmpdir, 'myfile.doc')
2728 ... with open(fn, 'w') as f:
2729 ... _ = f.write('This is a very simple test file.\n')
2730 ... _ = f.write(' >>> 1 + 1\n')
2731 ... _ = f.write(' 2\n')
2732 ... _ = f.write(' >>> "a"\n')
2733 ... _ = f.write(" 'a'\n")
2734 ... _ = f.write('\n')
2735 ... _ = f.write('And that is it.\n')
2736 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002737 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002738 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002739 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002740
2741With no arguments and passing tests, we should get no output:
2742
2743 >>> rc1, out1, err1
2744 (0, b'', b'')
2745
2746With the verbose flag, we should see the test output, but no error output:
2747
2748 >>> rc2, err2
2749 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002750 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002751 Trying:
2752 1 + 1
2753 Expecting:
2754 2
2755 ok
2756 Trying:
2757 "a"
2758 Expecting:
2759 'a'
2760 ok
2761 1 items passed all tests:
2762 2 tests in myfile.doc
2763 2 tests in 1 items.
2764 2 passed and 0 failed.
2765 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002766
2767Now we'll write a couple files, one with three tests, the other a python module
2768with two tests, both of the files having "errors" in the tests that can be made
2769non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2770the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002771allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002772ability to process more than one file on the command line and, since the second
2773file ends in '.py', its handling of python module files (as opposed to straight
2774text files).
2775
Berker Peksagce643912015-05-06 06:33:17 +03002776 >>> from test.support import script_helper, temp_dir
2777 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002778 ... fn = os.path.join(tmpdir, 'myfile.doc')
2779 ... with open(fn, 'w') as f:
2780 ... _ = f.write('This is another simple test file.\n')
2781 ... _ = f.write(' >>> 1 + 1\n')
2782 ... _ = f.write(' 2\n')
2783 ... _ = f.write(' >>> "abcdef"\n')
2784 ... _ = f.write(" 'a...f'\n")
2785 ... _ = f.write(' >>> "ajkml"\n')
2786 ... _ = f.write(" 'a...l'\n")
2787 ... _ = f.write('\n')
2788 ... _ = f.write('And that is it.\n')
2789 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2790 ... with open(fn2, 'w') as f:
2791 ... _ = f.write('def test_func():\n')
2792 ... _ = f.write(' \"\"\"\n')
2793 ... _ = f.write(' This is simple python test function.\n')
2794 ... _ = f.write(' >>> 1 + 1\n')
2795 ... _ = f.write(' 2\n')
2796 ... _ = f.write(' >>> "abc def"\n')
2797 ... _ = f.write(" 'abc def'\n")
2798 ... _ = f.write("\n")
2799 ... _ = f.write(' \"\"\"\n')
R David Murray5707d502013-06-23 14:24:13 -04002800 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002801 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002802 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002803 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002804 ... rc3, out3, err3 = script_helper.assert_python_ok(
2805 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002806 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002807 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002808 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002809 ... rc5, out5, err5 = script_helper.assert_python_ok(
2810 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002811 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002812
2813Our first test run will show the errors from the first file (doctest stops if a
2814file has errors). Note that doctest test-run error output appears on stdout,
2815not stderr:
2816
2817 >>> rc1, err1
2818 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002819 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002820 **********************************************************************
2821 File "...myfile.doc", line 4, in myfile.doc
2822 Failed example:
2823 "abcdef"
2824 Expected:
2825 'a...f'
2826 Got:
2827 'abcdef'
2828 **********************************************************************
2829 File "...myfile.doc", line 6, in myfile.doc
2830 Failed example:
2831 "ajkml"
2832 Expected:
2833 'a...l'
2834 Got:
2835 'ajkml'
2836 **********************************************************************
2837 1 items had failures:
2838 2 of 3 in myfile.doc
2839 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002840
2841With -o ELLIPSIS specified, the second run, against just the first file, should
2842produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2843should the third, which ran against both files:
2844
2845 >>> rc2, out2, err2
2846 (0, b'', b'')
2847 >>> rc3, out3, err3
2848 (0, b'', b'')
2849
2850The fourth run uses FAIL_FAST, so we should see only one error:
2851
2852 >>> rc4, err4
2853 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002854 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002855 **********************************************************************
2856 File "...myfile.doc", line 4, in myfile.doc
2857 Failed example:
2858 "abcdef"
2859 Expected:
2860 'a...f'
2861 Got:
2862 'abcdef'
2863 **********************************************************************
2864 1 items had failures:
2865 1 of 2 in myfile.doc
2866 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002867
2868The fifth test uses verbose with the two options, so we should get verbose
2869success output for the tests in both files:
2870
2871 >>> rc5, err5
2872 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002873 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002874 Trying:
2875 1 + 1
2876 Expecting:
2877 2
2878 ok
2879 Trying:
2880 "abcdef"
2881 Expecting:
2882 'a...f'
2883 ok
2884 Trying:
2885 "ajkml"
2886 Expecting:
2887 'a...l'
2888 ok
2889 1 items passed all tests:
2890 3 tests in myfile.doc
2891 3 tests in 1 items.
2892 3 passed and 0 failed.
2893 Test passed.
2894 Trying:
2895 1 + 1
2896 Expecting:
2897 2
2898 ok
2899 Trying:
2900 "abc def"
2901 Expecting:
2902 'abc def'
2903 ok
2904 1 items had no tests:
2905 myfile2
2906 1 items passed all tests:
2907 2 tests in myfile2.test_func
2908 2 tests in 2 items.
2909 2 passed and 0 failed.
2910 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002911
2912We should also check some typical error cases.
2913
2914Invalid file name:
2915
2916 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002917 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04002918 >>> rc, out
2919 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002920 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002921 Traceback (most recent call last):
2922 ...
2923 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
2924
2925Invalid doctest option:
2926
2927 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002928 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04002929 >>> rc, out
2930 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04002931 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002932 usage...invalid...nosuchoption...
2933
2934"""
2935
Tim Peters8485b562004-08-04 18:46:34 +00002936######################################################################
2937## Main
2938######################################################################
2939
2940def test_main():
2941 # Check the doctest cases in doctest itself:
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02002942 ret = support.run_doctest(doctest, verbosity=True)
Victor Stinner931602a2016-03-25 12:48:17 +01002943
Tim Peters8485b562004-08-04 18:46:34 +00002944 # Check the doctest cases defined here:
2945 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002946 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002947
Tim Peters8485b562004-08-04 18:46:34 +00002948def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002949 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01002950 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00002951 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002952 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002953 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002954 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002955 r.write_results(show_missing=True, summary=True,
2956 coverdir=coverdir)
2957
2958if __name__ == '__main__':
2959 if '-c' in sys.argv:
2960 test_coverage('/tmp/doctest.cover')
2961 else:
2962 test_main()