blob: aa92777efc3c7a815d967946ff77c38b198a7b63 [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
Jason R. Coombsb9650a02018-03-05 18:29:08 -050010import importlib
11import unittest
Nick Coghland5d9e022018-03-25 23:03:10 +100012import tempfile
Florent Xiclunadc6f2d02010-04-02 19:25:32 +000013
Nick Coghlanf088e5e2008-12-14 11:50:48 +000014# NOTE: There are some additional tests relating to interaction with
15# zipimport in the test_zipimport_support test module.
16
Tim Peters8485b562004-08-04 18:46:34 +000017######################################################################
18## Sample Objects (used by test cases)
19######################################################################
20
21def sample_func(v):
22 """
Tim Peters19397e52004-08-06 22:02:59 +000023 Blah blah
24
Guido van Rossum7131f842007-02-09 20:13:25 +000025 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000026 44
Tim Peters19397e52004-08-06 22:02:59 +000027
28 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000029 """
30 return v+v
31
32class SampleClass:
33 """
Guido van Rossum7131f842007-02-09 20:13:25 +000034 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000035 1
Edward Loper4ae900f2004-09-21 03:20:34 +000036
37 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
38 >>>
39 ...
40
41 Multiline example:
42 >>> sc = SampleClass(3)
43 >>> for i in range(10):
44 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000045 ... print(' ', sc.get(), sep='', end='')
46 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000047 """
48 def __init__(self, val):
49 """
Guido van Rossum7131f842007-02-09 20:13:25 +000050 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000051 12
52 """
53 self.val = val
54
55 def double(self):
56 """
Guido van Rossum7131f842007-02-09 20:13:25 +000057 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000058 24
59 """
60 return SampleClass(self.val + self.val)
61
62 def get(self):
63 """
Guido van Rossum7131f842007-02-09 20:13:25 +000064 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000065 -5
66 """
67 return self.val
68
69 def a_staticmethod(v):
70 """
Guido van Rossum7131f842007-02-09 20:13:25 +000071 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000072 11
73 """
74 return v+1
75 a_staticmethod = staticmethod(a_staticmethod)
76
77 def a_classmethod(cls, v):
78 """
Guido van Rossum7131f842007-02-09 20:13:25 +000079 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000080 12
Guido van Rossum7131f842007-02-09 20:13:25 +000081 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000082 12
83 """
84 return v+2
85 a_classmethod = classmethod(a_classmethod)
86
87 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000088 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000089 22
90 """)
91
92 class NestedClass:
93 """
94 >>> x = SampleClass.NestedClass(5)
95 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000096 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000097 25
98 """
99 def __init__(self, val=0):
100 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000101 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +0000102 0
103 """
104 self.val = val
105 def square(self):
106 return SampleClass.NestedClass(self.val*self.val)
107 def get(self):
108 return self.val
109
110class SampleNewStyleClass(object):
111 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000112 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000113 1
114 2
115 3
116 """
117 def __init__(self, val):
118 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000119 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000120 12
121 """
122 self.val = val
123
124 def double(self):
125 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000126 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000127 24
128 """
129 return SampleNewStyleClass(self.val + self.val)
130
131 def get(self):
132 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000133 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000134 -5
135 """
136 return self.val
137
138######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000139## Fake stdin (for testing interactive debugging)
140######################################################################
141
142class _FakeInput:
143 """
144 A fake input stream for pdb's interactive debugger. Whenever a
145 line is read, print it (to simulate the user typing it), and then
146 return it. The set of lines to return is specified in the
147 constructor; they should not have trailing newlines.
148 """
149 def __init__(self, lines):
150 self.lines = lines
151
152 def readline(self):
153 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000154 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000155 return line+'\n'
156
157######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000158## Test Cases
159######################################################################
160
161def test_Example(): r"""
162Unit tests for the `Example` class.
163
Edward Lopera6b68322004-08-26 00:05:43 +0000164Example is a simple container class that holds:
165 - `source`: A source string.
166 - `want`: An expected output string.
167 - `exc_msg`: An expected exception message string (or None if no
168 exception is expected).
169 - `lineno`: A line number (within the docstring).
170 - `indent`: The example's indentation in the input string.
171 - `options`: An option dictionary, mapping option flags to True or
172 False.
Tim Peters8485b562004-08-04 18:46:34 +0000173
Edward Lopera6b68322004-08-26 00:05:43 +0000174These attributes are set by the constructor. `source` and `want` are
175required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000176
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000177 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000178 >>> (example.source, example.want, example.exc_msg,
179 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000180 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000181
182The first three attributes (`source`, `want`, and `exc_msg`) may be
183specified positionally; the remaining arguments should be specified as
184keyword arguments:
185
186 >>> exc_msg = 'IndexError: pop from an empty list'
187 >>> example = doctest.Example('[].pop()', '', exc_msg,
188 ... lineno=5, indent=4,
189 ... options={doctest.ELLIPSIS: True})
190 >>> (example.source, example.want, example.exc_msg,
191 ... example.lineno, example.indent, example.options)
192 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
193
194The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000195
Tim Petersbb431472004-08-09 03:51:46 +0000196 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000197 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000198 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000199 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000200
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000201 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000202 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000203 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000204
Tim Petersbb431472004-08-09 03:51:46 +0000205 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000206 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000207 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000208 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000209
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000210 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000211 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000212 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000213
Edward Lopera6b68322004-08-26 00:05:43 +0000214 Empty source string (which should never appear in real examples)
215 >>> e = doctest.Example('', '')
216 >>> e.source, e.want
217 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000218
Edward Lopera6b68322004-08-26 00:05:43 +0000219The constructor normalizes the `want` string to end in a newline,
220unless it's the empty string:
221
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000222 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000223 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000224 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000225
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000226 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000227 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000228 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000229
Edward Lopera6b68322004-08-26 00:05:43 +0000230 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000231 >>> e.source, e.want
232 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000233
234The constructor normalizes the `exc_msg` string to end in a newline,
235unless it's `None`:
236
237 Message spans one line
238 >>> exc_msg = 'IndexError: pop from an empty list'
239 >>> e = doctest.Example('[].pop()', '', exc_msg)
240 >>> e.exc_msg
241 'IndexError: pop from an empty list\n'
242
243 >>> exc_msg = 'IndexError: pop from an empty list\n'
244 >>> e = doctest.Example('[].pop()', '', exc_msg)
245 >>> e.exc_msg
246 'IndexError: pop from an empty list\n'
247
248 Message spans multiple lines
249 >>> exc_msg = 'ValueError: 1\n 2'
250 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
251 >>> e.exc_msg
252 'ValueError: 1\n 2\n'
253
254 >>> exc_msg = 'ValueError: 1\n 2\n'
255 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
256 >>> e.exc_msg
257 'ValueError: 1\n 2\n'
258
259 Empty (but non-None) exception message (which should never appear
260 in real examples)
261 >>> exc_msg = ''
262 >>> e = doctest.Example('raise X()', '', exc_msg)
263 >>> e.exc_msg
264 '\n'
Antoine Pitrou165b1282011-12-18 20:20:17 +0100265
266Compare `Example`:
267 >>> example = doctest.Example('print 1', '1\n')
268 >>> same_example = doctest.Example('print 1', '1\n')
269 >>> other_example = doctest.Example('print 42', '42\n')
270 >>> example == same_example
271 True
272 >>> example != same_example
273 False
274 >>> hash(example) == hash(same_example)
275 True
276 >>> example == other_example
277 False
278 >>> example != other_example
279 True
Tim Peters8485b562004-08-04 18:46:34 +0000280"""
281
282def test_DocTest(): r"""
283Unit tests for the `DocTest` class.
284
285DocTest is a collection of examples, extracted from a docstring, along
286with information about where the docstring comes from (a name,
287filename, and line number). The docstring is parsed by the `DocTest`
288constructor:
289
290 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000291 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000292 ... 12
293 ...
294 ... Non-example text.
295 ...
R David Murray44b548d2016-09-08 13:59:53 -0400296 ... >>> print('another\\example')
Tim Peters8485b562004-08-04 18:46:34 +0000297 ... another
298 ... example
299 ... '''
300 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000301 >>> parser = doctest.DocTestParser()
302 >>> test = parser.get_doctest(docstring, globs, 'some_test',
303 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000304 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000305 <DocTest some_test from some_file:20 (2 examples)>
306 >>> len(test.examples)
307 2
308 >>> e1, e2 = test.examples
309 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000310 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000311 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000312 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000313
314Source information (name, filename, and line number) is available as
315attributes on the doctest object:
316
317 >>> (test.name, test.filename, test.lineno)
318 ('some_test', 'some_file', 20)
319
320The line number of an example within its containing file is found by
321adding the line number of the example and the line number of its
322containing test:
323
324 >>> test.lineno + e1.lineno
325 21
326 >>> test.lineno + e2.lineno
327 26
328
Martin Panter46f50722016-05-26 05:35:26 +0000329If the docstring contains inconsistent leading whitespace in the
Tim Peters8485b562004-08-04 18:46:34 +0000330expected output of an example, then `DocTest` will raise a ValueError:
331
332 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000333 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000334 ... bad
335 ... indentation
336 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000337 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000338 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000339 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000340
341If the docstring contains inconsistent leading whitespace on
342continuation lines, then `DocTest` will raise a ValueError:
343
344 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000345 ... >>> print(('bad indentation',
346 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000347 ... ('bad', 'indentation')
348 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000349 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000350 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000351 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000352
353If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
354will raise a ValueError:
355
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000356 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000357 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000358 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000359 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000360
361If there's no blank space after a PS2 prompt ('...'), then `DocTest`
362will raise a ValueError:
363
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000364 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000365 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000366 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000367 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000368
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100369Compare `DocTest`:
370
371 >>> docstring = '''
372 ... >>> print 12
373 ... 12
374 ... '''
375 >>> test = parser.get_doctest(docstring, globs, 'some_test',
376 ... 'some_test', 20)
377 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
378 ... 'some_test', 20)
379 >>> test == same_test
380 True
381 >>> test != same_test
382 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100383 >>> hash(test) == hash(same_test)
384 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100385 >>> docstring = '''
386 ... >>> print 42
387 ... 42
388 ... '''
389 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
390 ... 'other_file', 10)
391 >>> test == other_test
392 False
393 >>> test != other_test
394 True
395
396Compare `DocTestCase`:
397
398 >>> DocTestCase = doctest.DocTestCase
399 >>> test_case = DocTestCase(test)
400 >>> same_test_case = DocTestCase(same_test)
401 >>> other_test_case = DocTestCase(other_test)
402 >>> test_case == same_test_case
403 True
404 >>> test_case != same_test_case
405 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100406 >>> hash(test_case) == hash(same_test_case)
407 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100408 >>> test == other_test_case
409 False
410 >>> test != other_test_case
411 True
412
Tim Peters8485b562004-08-04 18:46:34 +0000413"""
414
Zachary Ware7119b452013-11-24 02:21:57 -0600415class test_DocTestFinder:
416 def basics(): r"""
Tim Peters8485b562004-08-04 18:46:34 +0000417Unit tests for the `DocTestFinder` class.
418
419DocTestFinder is used to extract DocTests from an object's docstring
420and the docstrings of its contained objects. It can be used with
421modules, functions, classes, methods, staticmethods, classmethods, and
422properties.
423
424Finding Tests in Functions
425~~~~~~~~~~~~~~~~~~~~~~~~~~
426For a function whose docstring contains examples, DocTestFinder.find()
427will return a single test (for that function's docstring):
428
Tim Peters8485b562004-08-04 18:46:34 +0000429 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000430
431We'll simulate a __file__ attr that ends in pyc:
432
433 >>> import test.test_doctest
434 >>> old = test.test_doctest.__file__
435 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
436
Tim Peters8485b562004-08-04 18:46:34 +0000437 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000438
Guido van Rossum7131f842007-02-09 20:13:25 +0000439 >>> print(tests) # doctest: +ELLIPSIS
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500440 [<DocTest sample_func from ...:21 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000441
Tim Peters4de7c5c2004-08-23 22:38:05 +0000442The exact name depends on how test_doctest was invoked, so allow for
443leading path components.
444
445 >>> tests[0].filename # doctest: +ELLIPSIS
446 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000447
448 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000449
Jim Fulton07a349c2004-08-22 14:10:00 +0000450
Tim Peters8485b562004-08-04 18:46:34 +0000451 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000452 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000453 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000454
Edward Loper32ddbf72004-09-13 05:47:24 +0000455By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000456
457 >>> def no_docstring(v):
458 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000459 >>> finder.find(no_docstring)
460 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000461
462However, the optional argument `exclude_empty` to the DocTestFinder
463constructor can be used to exclude tests for objects with empty
464docstrings:
465
466 >>> def no_docstring(v):
467 ... pass
468 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
469 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000470 []
471
472If the function has a docstring with no examples, then a test with no
473examples is returned. (This lets `DocTestRunner` collect statistics
474about which functions have no tests -- but is that useful? And should
475an empty test also be created when there's no docstring?)
476
477 >>> def no_examples(v):
478 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000479 >>> finder.find(no_examples) # doctest: +ELLIPSIS
480 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000481
482Finding Tests in Classes
483~~~~~~~~~~~~~~~~~~~~~~~~
484For a class, DocTestFinder will create a test for the class's
485docstring, and will recursively explore its contents, including
486methods, classmethods, staticmethods, properties, and nested classes.
487
488 >>> finder = doctest.DocTestFinder()
489 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000490 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000491 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000492 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000493 3 SampleClass.NestedClass
494 1 SampleClass.NestedClass.__init__
495 1 SampleClass.__init__
496 2 SampleClass.a_classmethod
497 1 SampleClass.a_property
498 1 SampleClass.a_staticmethod
499 1 SampleClass.double
500 1 SampleClass.get
501
502New-style classes are also supported:
503
504 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000505 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000506 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000507 1 SampleNewStyleClass
508 1 SampleNewStyleClass.__init__
509 1 SampleNewStyleClass.double
510 1 SampleNewStyleClass.get
511
512Finding Tests in Modules
513~~~~~~~~~~~~~~~~~~~~~~~~
514For a module, DocTestFinder will create a test for the class's
515docstring, and will recursively explore its contents, including
516functions, classes, and the `__test__` dictionary, if it exists:
517
518 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000519 >>> import types
520 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000521 >>> def triple(val):
522 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000523 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000524 ... 33
525 ... '''
526 ... return val*3
527 >>> m.__dict__.update({
528 ... 'sample_func': sample_func,
529 ... 'SampleClass': SampleClass,
530 ... '__doc__': '''
531 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000532 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000533 ... module
534 ... ''',
535 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000536 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000537 ... 'c': triple}})
538
539 >>> finder = doctest.DocTestFinder()
540 >>> # Use module=test.test_doctest, to prevent doctest from
541 >>> # ignoring the objects since they weren't defined in m.
542 >>> import test.test_doctest
543 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000544 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000545 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000546 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000547 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000548 3 some_module.SampleClass.NestedClass
549 1 some_module.SampleClass.NestedClass.__init__
550 1 some_module.SampleClass.__init__
551 2 some_module.SampleClass.a_classmethod
552 1 some_module.SampleClass.a_property
553 1 some_module.SampleClass.a_staticmethod
554 1 some_module.SampleClass.double
555 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000556 1 some_module.__test__.c
557 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000558 1 some_module.sample_func
559
560Duplicate Removal
561~~~~~~~~~~~~~~~~~
562If a single object is listed twice (under different names), then tests
563will only be generated for it once:
564
Tim Petersf3f57472004-08-08 06:11:48 +0000565 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000566 >>> assert doctest_aliases.TwoNames.f
567 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000568 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000569 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000570 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000571 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000572 test.doctest_aliases.TwoNames
573
574 TwoNames.f and TwoNames.g are bound to the same object.
575 We can't guess which will be found in doctest's traversal of
576 TwoNames.__dict__ first, so we have to allow for either.
577
578 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000579 True
580
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000581Empty Tests
582~~~~~~~~~~~
583By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000584
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000585 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000586 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000587 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000588 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000589 3 SampleClass.NestedClass
590 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000591 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000592 2 SampleClass.a_classmethod
593 1 SampleClass.a_property
594 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000595 1 SampleClass.double
596 1 SampleClass.get
597
598By default, that excluded objects with no doctests. exclude_empty=False
599tells it to include (empty) tests for objects with no doctests. This feature
600is really to support backward compatibility in what doctest.master.summarize()
601displays.
602
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000603 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000604 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000605 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000606 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000607 3 SampleClass.NestedClass
608 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000609 0 SampleClass.NestedClass.get
610 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000611 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000612 2 SampleClass.a_classmethod
613 1 SampleClass.a_property
614 1 SampleClass.a_staticmethod
615 1 SampleClass.double
616 1 SampleClass.get
617
Tim Peters8485b562004-08-04 18:46:34 +0000618Turning off Recursion
619~~~~~~~~~~~~~~~~~~~~~
620DocTestFinder can be told not to look for tests in contained objects
621using the `recurse` flag:
622
623 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000624 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000625 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000626 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000627
628Line numbers
629~~~~~~~~~~~~
630DocTestFinder finds the line number of each example:
631
632 >>> def f(x):
633 ... '''
634 ... >>> x = 12
635 ...
636 ... some text
637 ...
638 ... >>> # examples are not created for comments & bare prompts.
639 ... >>>
640 ... ...
641 ...
642 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000643 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000645 ... >>> x//2
646 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000647 ... '''
648 >>> test = doctest.DocTestFinder().find(f)[0]
649 >>> [e.lineno for e in test.examples]
650 [1, 9, 12]
Zachary Ware7119b452013-11-24 02:21:57 -0600651"""
652
653 if int.__doc__: # simple check for --without-doc-strings, skip if lacking
654 def non_Python_modules(): r"""
Zachary Warea4b7a752013-11-24 01:19:09 -0600655
656Finding Doctests in Modules Not Written in Python
657~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
658DocTestFinder can also find doctests in most modules not written in Python.
659We'll use builtins as an example, since it almost certainly isn't written in
660plain ol' Python and is guaranteed to be available.
661
662 >>> import builtins
663 >>> tests = doctest.DocTestFinder().find(builtins)
INADA Naokia49ac992018-01-27 14:06:21 +0900664 >>> 800 < len(tests) < 820 # approximate number of objects with docstrings
Zachary Ware7119b452013-11-24 02:21:57 -0600665 True
Zachary Warea4b7a752013-11-24 01:19:09 -0600666 >>> real_tests = [t for t in tests if len(t.examples) > 0]
Zachary Ware7119b452013-11-24 02:21:57 -0600667 >>> len(real_tests) # objects that actually have doctests
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700668 12
Zachary Warea4b7a752013-11-24 01:19:09 -0600669 >>> for t in real_tests:
670 ... print('{} {}'.format(len(t.examples), t.name))
671 ...
672 1 builtins.bin
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700673 5 builtins.bytearray.hex
674 5 builtins.bytes.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600675 3 builtins.float.as_integer_ratio
676 2 builtins.float.fromhex
677 2 builtins.float.hex
678 1 builtins.hex
679 1 builtins.int
Lisa Roach5ac70432018-09-13 23:56:23 -0700680 3 builtins.int.as_integer_ratio
Zachary Warea4b7a752013-11-24 01:19:09 -0600681 2 builtins.int.bit_length
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700682 5 builtins.memoryview.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600683 1 builtins.oct
684
685Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
686'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
687and 'int' is a type.
Tim Peters8485b562004-08-04 18:46:34 +0000688"""
689
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500690
691class TestDocTestFinder(unittest.TestCase):
692
693 def test_empty_namespace_package(self):
694 pkg_name = 'doctest_empty_pkg'
Nick Coghland5d9e022018-03-25 23:03:10 +1000695 with tempfile.TemporaryDirectory() as parent_dir:
696 pkg_dir = os.path.join(parent_dir, pkg_name)
697 os.mkdir(pkg_dir)
698 sys.path.append(parent_dir)
699 try:
700 mod = importlib.import_module(pkg_name)
701 finally:
702 support.forget(pkg_name)
703 sys.path.pop()
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500704
Xtreak8289e272019-12-13 23:36:53 +0530705 include_empty_finder = doctest.DocTestFinder(exclude_empty=False)
706 exclude_empty_finder = doctest.DocTestFinder(exclude_empty=True)
707
708 self.assertEqual(len(include_empty_finder.find(mod)), 1)
709 self.assertEqual(len(exclude_empty_finder.find(mod)), 0)
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500710
Edward Loper00f8da72004-08-26 18:05:07 +0000711def test_DocTestParser(): r"""
712Unit tests for the `DocTestParser` class.
713
714DocTestParser is used to parse docstrings containing doctest examples.
715
716The `parse` method divides a docstring into examples and intervening
717text:
718
719 >>> s = '''
720 ... >>> x, y = 2, 3 # no output expected
721 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000722 ... ... print(x)
723 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000724 ... 2
725 ... 3
726 ...
727 ... Some text.
728 ... >>> x+y
729 ... 5
730 ... '''
731 >>> parser = doctest.DocTestParser()
732 >>> for piece in parser.parse(s):
733 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000734 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000735 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000736 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000737 Text: '\n'
738 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
739 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000740 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000741 Text: '\nSome text.\n'
742 Example: ('x+y\n', '5\n', 9)
743 Text: ''
744
745The `get_examples` method returns just the examples:
746
747 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000748 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000749 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000750 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000751 ('x+y\n', '5\n', 9)
752
753The `get_doctest` method creates a Test from the examples, along with the
754given arguments:
755
756 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
757 >>> (test.name, test.filename, test.lineno)
758 ('name', 'filename', 5)
759 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000760 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000761 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000762 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000763 ('x+y\n', '5\n', 9)
764"""
765
Tim Peters8485b562004-08-04 18:46:34 +0000766class test_DocTestRunner:
767 def basics(): r"""
768Unit tests for the `DocTestRunner` class.
769
770DocTestRunner is used to run DocTest test cases, and to accumulate
771statistics. Here's a simple DocTest case we can use:
772
773 >>> def f(x):
774 ... '''
775 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000776 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000777 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000778 ... >>> x//2
779 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000780 ... '''
781 >>> test = doctest.DocTestFinder().find(f)[0]
782
783The main DocTestRunner interface is the `run` method, which runs a
784given DocTest case in a given namespace (globs). It returns a tuple
785`(f,t)`, where `f` is the number of failed tests and `t` is the number
786of tried tests.
787
788 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000789 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000790
791If any example produces incorrect output, then the test runner reports
792the failure and proceeds to the next example:
793
794 >>> def f(x):
795 ... '''
796 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000797 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000798 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000799 ... >>> x//2
800 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000801 ... '''
802 >>> test = doctest.DocTestFinder().find(f)[0]
803 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000804 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000805 Trying:
806 x = 12
807 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000808 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000809 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000810 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000811 Expecting:
812 14
Tim Peters8485b562004-08-04 18:46:34 +0000813 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000814 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000815 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000816 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000817 Expected:
818 14
819 Got:
820 12
Edward Loperaacf0832004-08-26 01:19:50 +0000821 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000822 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000823 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000824 6
Tim Peters8485b562004-08-04 18:46:34 +0000825 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000826 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000827"""
828 def verbose_flag(): r"""
829The `verbose` flag makes the test runner generate more detailed
830output:
831
832 >>> def f(x):
833 ... '''
834 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000835 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000836 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000837 ... >>> x//2
838 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000839 ... '''
840 >>> test = doctest.DocTestFinder().find(f)[0]
841
842 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000843 Trying:
844 x = 12
845 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000846 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000847 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000848 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000849 Expecting:
850 12
Tim Peters8485b562004-08-04 18:46:34 +0000851 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000852 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000853 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000854 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000855 6
Tim Peters8485b562004-08-04 18:46:34 +0000856 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000857 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000858
859If the `verbose` flag is unspecified, then the output will be verbose
860iff `-v` appears in sys.argv:
861
862 >>> # Save the real sys.argv list.
863 >>> old_argv = sys.argv
864
865 >>> # If -v does not appear in sys.argv, then output isn't verbose.
866 >>> sys.argv = ['test']
867 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000868 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000869
870 >>> # If -v does appear in sys.argv, then output is verbose.
871 >>> sys.argv = ['test', '-v']
872 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000873 Trying:
874 x = 12
875 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000876 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000877 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000878 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000879 Expecting:
880 12
Tim Peters8485b562004-08-04 18:46:34 +0000881 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000882 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000883 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000884 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000885 6
Tim Peters8485b562004-08-04 18:46:34 +0000886 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000887 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000888
889 >>> # Restore sys.argv
890 >>> sys.argv = old_argv
891
892In the remaining examples, the test runner's verbosity will be
893explicitly set, to ensure that the test behavior is consistent.
894 """
895 def exceptions(): r"""
896Tests of `DocTestRunner`'s exception handling.
897
898An expected exception is specified with a traceback message. The
899lines between the first line and the type/value may be omitted or
900replaced with any other string:
901
902 >>> def f(x):
903 ... '''
904 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000905 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000906 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000907 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000908 ... '''
909 >>> test = doctest.DocTestFinder().find(f)[0]
910 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000911 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000912
Edward Loper19b19582004-08-25 23:07:03 +0000913An example may not generate output before it raises an exception; if
914it does, then the traceback message will not be recognized as
915signaling an expected exception, so the example will be reported as an
916unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000917
918 >>> def f(x):
919 ... '''
920 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000921 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000922 ... pre-exception output
923 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000924 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000925 ... '''
926 >>> test = doctest.DocTestFinder().find(f)[0]
927 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000928 ... # doctest: +ELLIPSIS
929 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000930 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000931 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000932 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000933 Exception raised:
934 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000935 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000936 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000937
938Exception messages may contain newlines:
939
940 >>> def f(x):
941 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000942 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000943 ... Traceback (most recent call last):
944 ... ValueError: multi
945 ... line
946 ... message
947 ... '''
948 >>> test = doctest.DocTestFinder().find(f)[0]
949 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000950 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000951
952If an exception is expected, but an exception with the wrong type or
953message is raised, then it is reported as a failure:
954
955 >>> def f(x):
956 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000957 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000958 ... Traceback (most recent call last):
959 ... ValueError: wrong message
960 ... '''
961 >>> test = doctest.DocTestFinder().find(f)[0]
962 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000963 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000964 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000965 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000966 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000967 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000968 Expected:
969 Traceback (most recent call last):
970 ValueError: wrong message
971 Got:
972 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000973 ...
Tim Peters8485b562004-08-04 18:46:34 +0000974 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000975 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000976
Tim Peters1fbf9c52004-09-04 17:21:02 +0000977However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
978detail:
979
980 >>> def f(x):
981 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000982 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000983 ... Traceback (most recent call last):
984 ... ValueError: wrong message
985 ... '''
986 >>> test = doctest.DocTestFinder().find(f)[0]
987 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000988 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000989
Nick Coghlan5e76e942010-06-12 13:42:46 +0000990IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
991between Python versions. For example, in Python 2.x, the module path of
992the exception is not in the output, but this will fail under Python 3:
993
994 >>> def f(x):
995 ... r'''
996 ... >>> from http.client import HTTPException
997 ... >>> raise HTTPException('message')
998 ... Traceback (most recent call last):
999 ... HTTPException: message
1000 ... '''
1001 >>> test = doctest.DocTestFinder().find(f)[0]
1002 >>> doctest.DocTestRunner(verbose=False).run(test)
1003 ... # doctest: +ELLIPSIS
1004 **********************************************************************
1005 File ..., line 4, in f
1006 Failed example:
1007 raise HTTPException('message')
1008 Expected:
1009 Traceback (most recent call last):
1010 HTTPException: message
1011 Got:
1012 Traceback (most recent call last):
1013 ...
1014 http.client.HTTPException: message
1015 TestResults(failed=1, attempted=2)
1016
1017But in Python 3 the module path is included, and therefore a test must look
1018like the following test to succeed in Python 3. But that test will fail under
1019Python 2.
1020
1021 >>> def f(x):
1022 ... r'''
1023 ... >>> from http.client import HTTPException
1024 ... >>> raise HTTPException('message')
1025 ... Traceback (most recent call last):
1026 ... http.client.HTTPException: message
1027 ... '''
1028 >>> test = doctest.DocTestFinder().find(f)[0]
1029 >>> doctest.DocTestRunner(verbose=False).run(test)
1030 TestResults(failed=0, attempted=2)
1031
1032However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1033(or its unexpected absence) will be ignored:
1034
1035 >>> def f(x):
1036 ... r'''
1037 ... >>> from http.client import HTTPException
1038 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1039 ... Traceback (most recent call last):
1040 ... HTTPException: message
1041 ... '''
1042 >>> test = doctest.DocTestFinder().find(f)[0]
1043 >>> doctest.DocTestRunner(verbose=False).run(test)
1044 TestResults(failed=0, attempted=2)
1045
1046The module path will be completely ignored, so two different module paths will
1047still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1048be used when exceptions have changed module.
1049
1050 >>> def f(x):
1051 ... r'''
1052 ... >>> from http.client import HTTPException
1053 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1054 ... Traceback (most recent call last):
1055 ... foo.bar.HTTPException: message
1056 ... '''
1057 >>> test = doctest.DocTestFinder().find(f)[0]
1058 >>> doctest.DocTestRunner(verbose=False).run(test)
1059 TestResults(failed=0, attempted=2)
1060
Tim Peters1fbf9c52004-09-04 17:21:02 +00001061But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1062
1063 >>> def f(x):
1064 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001065 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001066 ... Traceback (most recent call last):
1067 ... TypeError: wrong type
1068 ... '''
1069 >>> test = doctest.DocTestFinder().find(f)[0]
1070 >>> doctest.DocTestRunner(verbose=False).run(test)
1071 ... # doctest: +ELLIPSIS
1072 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001073 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001074 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001075 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001076 Expected:
1077 Traceback (most recent call last):
1078 TypeError: wrong type
1079 Got:
1080 Traceback (most recent call last):
1081 ...
1082 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001083 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001084
Tim Petersf9a07f22013-12-03 21:02:05 -06001085If the exception does not have a message, you can still use
1086IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1087
1088 >>> def f(x):
1089 ... r'''
1090 ... >>> from http.client import HTTPException
1091 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1092 ... Traceback (most recent call last):
1093 ... foo.bar.HTTPException
1094 ... '''
1095 >>> test = doctest.DocTestFinder().find(f)[0]
1096 >>> doctest.DocTestRunner(verbose=False).run(test)
1097 TestResults(failed=0, attempted=2)
1098
1099Note that a trailing colon doesn't matter either:
1100
1101 >>> def f(x):
1102 ... r'''
1103 ... >>> from http.client import HTTPException
1104 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1105 ... Traceback (most recent call last):
1106 ... foo.bar.HTTPException:
1107 ... '''
1108 >>> test = doctest.DocTestFinder().find(f)[0]
1109 >>> doctest.DocTestRunner(verbose=False).run(test)
1110 TestResults(failed=0, attempted=2)
1111
Tim Peters8485b562004-08-04 18:46:34 +00001112If an exception is raised but not expected, then it is reported as an
1113unexpected exception:
1114
Tim Peters8485b562004-08-04 18:46:34 +00001115 >>> def f(x):
1116 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001117 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001118 ... 0
1119 ... '''
1120 >>> test = doctest.DocTestFinder().find(f)[0]
1121 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001122 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001123 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001124 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001125 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001126 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001127 Exception raised:
1128 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001129 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001130 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001131 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001132"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001133 def displayhook(): r"""
1134Test that changing sys.displayhook doesn't matter for doctest.
1135
1136 >>> import sys
1137 >>> orig_displayhook = sys.displayhook
1138 >>> def my_displayhook(x):
1139 ... print('hi!')
1140 >>> sys.displayhook = my_displayhook
1141 >>> def f():
1142 ... '''
1143 ... >>> 3
1144 ... 3
1145 ... '''
1146 >>> test = doctest.DocTestFinder().find(f)[0]
1147 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1148 >>> post_displayhook = sys.displayhook
1149
1150 We need to restore sys.displayhook now, so that we'll be able to test
1151 results.
1152
1153 >>> sys.displayhook = orig_displayhook
1154
1155 Ok, now we can check that everything is ok.
1156
1157 >>> r
1158 TestResults(failed=0, attempted=1)
1159 >>> post_displayhook is my_displayhook
1160 True
1161"""
Tim Peters8485b562004-08-04 18:46:34 +00001162 def optionflags(): r"""
1163Tests of `DocTestRunner`'s option flag handling.
1164
1165Several option flags can be used to customize the behavior of the test
1166runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001167to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001168together).
1169
1170The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1171and 1/0:
1172
1173 >>> def f(x):
1174 ... '>>> True\n1\n'
1175
1176 >>> # Without the flag:
1177 >>> test = doctest.DocTestFinder().find(f)[0]
1178 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001179 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001180
1181 >>> # With the flag:
1182 >>> test = doctest.DocTestFinder().find(f)[0]
1183 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1184 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001185 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001186 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001187 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001188 Failed example:
1189 True
1190 Expected:
1191 1
1192 Got:
1193 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001194 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001195
1196The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1197and the '<BLANKLINE>' marker:
1198
1199 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001200 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001201
1202 >>> # Without the flag:
1203 >>> test = doctest.DocTestFinder().find(f)[0]
1204 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001205 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001206
1207 >>> # With the flag:
1208 >>> test = doctest.DocTestFinder().find(f)[0]
1209 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1210 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001211 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001212 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001213 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001214 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001215 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001216 Expected:
1217 a
1218 <BLANKLINE>
1219 b
1220 Got:
1221 a
1222 <BLANKLINE>
1223 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001224 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001225
1226The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1227treated as equal:
1228
1229 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001230 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001231
1232 >>> # Without the flag:
1233 >>> test = doctest.DocTestFinder().find(f)[0]
1234 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001235 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001236 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001237 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001238 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001239 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001240 Expected:
1241 1 2
1242 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001243 Got:
1244 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001245 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001246
1247 >>> # With the flag:
1248 >>> test = doctest.DocTestFinder().find(f)[0]
1249 >>> flags = doctest.NORMALIZE_WHITESPACE
1250 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001251 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001252
Tim Peters026f8dc2004-08-19 16:38:58 +00001253 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001254 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001255 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1256 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1257
Tim Peters8485b562004-08-04 18:46:34 +00001258The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1259output to match any substring in the actual output:
1260
1261 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001262 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001263
1264 >>> # Without the flag:
1265 >>> test = doctest.DocTestFinder().find(f)[0]
1266 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001267 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001268 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001269 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001270 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001271 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001272 Expected:
1273 [0, 1, 2, ..., 14]
1274 Got:
1275 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001276 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001277
1278 >>> # With the flag:
1279 >>> test = doctest.DocTestFinder().find(f)[0]
1280 >>> flags = doctest.ELLIPSIS
1281 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001282 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001283
Tim Peterse594bee2004-08-22 01:47:51 +00001284 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001285
Guido van Rossume0192e52007-02-09 23:39:59 +00001286 >>> if 1:
1287 ... for i in range(100):
1288 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1289 ... print('!')
1290 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001291
Tim Peters026f8dc2004-08-19 16:38:58 +00001292 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001293
Guido van Rossume0192e52007-02-09 23:39:59 +00001294 >>> if 1: #doctest: +ELLIPSIS
1295 ... for i in range(20):
1296 ... print(i, end=' ')
1297 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001298 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001299
Tim Peters026f8dc2004-08-19 16:38:58 +00001300 Examples from the docs:
1301
Guido van Rossum805365e2007-05-07 22:24:25 +00001302 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001303 [0, 1, ..., 18, 19]
1304
Guido van Rossum805365e2007-05-07 22:24:25 +00001305 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001306 ... # doctest: +NORMALIZE_WHITESPACE
1307 [0, 1, ..., 18, 19]
1308
Thomas Wouters477c8d52006-05-27 19:21:47 +00001309The SKIP flag causes an example to be skipped entirely. I.e., the
1310example is not run. It can be useful in contexts where doctest
1311examples serve as both documentation and test cases, and an example
1312should be included for documentation purposes, but should not be
1313checked (e.g., because its output is random, or depends on resources
1314which would be unavailable.) The SKIP flag can also be used for
1315'commenting out' broken examples.
1316
1317 >>> import unavailable_resource # doctest: +SKIP
1318 >>> unavailable_resource.do_something() # doctest: +SKIP
1319 >>> unavailable_resource.blow_up() # doctest: +SKIP
1320 Traceback (most recent call last):
1321 ...
1322 UncheckedBlowUpError: Nobody checks me.
1323
1324 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001325 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001326 0.721216923889
1327
Edward Loper71f55af2004-08-26 01:41:51 +00001328The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001329and actual outputs to be displayed using a unified diff:
1330
1331 >>> def f(x):
1332 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001333 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001334 ... a
1335 ... B
1336 ... c
1337 ... d
1338 ... f
1339 ... g
1340 ... h
1341 ... '''
1342
1343 >>> # Without the flag:
1344 >>> test = doctest.DocTestFinder().find(f)[0]
1345 >>> doctest.DocTestRunner(verbose=False).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'))
Tim Peters8485b562004-08-04 18:46:34 +00001351 Expected:
1352 a
1353 B
1354 c
1355 d
1356 f
1357 g
1358 h
1359 Got:
1360 a
1361 b
1362 c
1363 d
1364 e
1365 f
1366 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001367 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001368
1369 >>> # With the flag:
1370 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001371 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001372 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001373 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001374 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001375 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001376 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001377 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001378 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001379 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001380 a
1381 -B
1382 +b
1383 c
1384 d
1385 +e
1386 f
1387 g
1388 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001389 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001390
Edward Loper71f55af2004-08-26 01:41:51 +00001391The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001392and actual outputs to be displayed using a context diff:
1393
Edward Loper71f55af2004-08-26 01:41:51 +00001394 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001395 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001396 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001397 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001398 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001399 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001400 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001401 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001402 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001403 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001404 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001405 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001406 a
1407 ! B
1408 c
1409 d
1410 f
1411 g
1412 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001413 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001414 a
1415 ! b
1416 c
1417 d
1418 + e
1419 f
1420 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001421 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001422
1423
Edward Loper71f55af2004-08-26 01:41:51 +00001424The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001425used by the popular ndiff.py utility. This does intraline difference
1426marking, as well as interline differences.
1427
1428 >>> def f(x):
1429 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001430 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001431 ... a b c d e f g h i j k 1 m
1432 ... '''
1433 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001434 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001435 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001436 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001437 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001438 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001439 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001440 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001441 Differences (ndiff with -expected +actual):
1442 - a b c d e f g h i j k 1 m
1443 ? ^
1444 + a b c d e f g h i j k l m
1445 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001446 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001447
Ezio Melotti13925002011-03-16 11:05:33 +02001448The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001449failing example:
1450
1451 >>> def f(x):
1452 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001453 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001454 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001455 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001456 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001457 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001458 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001459 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001460 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001461 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001462 ... 500
1463 ... '''
1464 >>> test = doctest.DocTestFinder().find(f)[0]
1465 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1466 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001467 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001468 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001469 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001470 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001471 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001472 Expected:
1473 200
1474 Got:
1475 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001476 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001477
Ezio Melotti13925002011-03-16 11:05:33 +02001478However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001479
1480 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001481 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001482 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001483 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001484 Expecting:
1485 1
1486 ok
1487 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001488 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001489 Expecting:
1490 200
1491 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001492 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001493 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001494 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001495 Expected:
1496 200
1497 Got:
1498 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001499 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001500
R David Murray5a9d7062012-11-21 15:09:21 -05001501The FAIL_FAST flag causes the runner to exit after the first failing example,
1502so subsequent examples are not even attempted:
1503
1504 >>> flags = doctest.FAIL_FAST
1505 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1506 ... # doctest: +ELLIPSIS
1507 **********************************************************************
1508 File ..., line 5, in f
1509 Failed example:
1510 print(2) # first failure
1511 Expected:
1512 200
1513 Got:
1514 2
1515 TestResults(failed=1, attempted=2)
1516
1517Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1518FAIL_FAST only:
1519
1520 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1521 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1522 ... # doctest: +ELLIPSIS
1523 **********************************************************************
1524 File ..., line 5, in f
1525 Failed example:
1526 print(2) # first failure
1527 Expected:
1528 200
1529 Got:
1530 2
1531 TestResults(failed=1, attempted=2)
1532
1533For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1534exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001535
1536 >>> def f(x):
1537 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001538 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001539 ... 1
1540 ... >>> raise ValueError(2) # first failure
1541 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001542 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001543 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001544 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001545 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001546 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001547 ... 500
1548 ... '''
1549 >>> test = doctest.DocTestFinder().find(f)[0]
1550 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1551 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1552 ... # doctest: +ELLIPSIS
1553 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001554 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001555 Failed example:
1556 raise ValueError(2) # first failure
1557 Exception raised:
1558 ...
1559 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001560 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001561 >>> flags = doctest.FAIL_FAST
1562 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1563 ... # doctest: +ELLIPSIS
1564 **********************************************************************
1565 File ..., line 5, in f
1566 Failed example:
1567 raise ValueError(2) # first failure
1568 Exception raised:
1569 ...
1570 ValueError: 2
1571 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001572
Thomas Wouters477c8d52006-05-27 19:21:47 +00001573New option flags can also be registered, via register_optionflag(). Here
1574we reach into doctest's internals a bit.
1575
1576 >>> unlikely = "UNLIKELY_OPTION_NAME"
1577 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1578 False
1579 >>> new_flag_value = doctest.register_optionflag(unlikely)
1580 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1581 True
1582
1583Before 2.4.4/2.5, registering a name more than once erroneously created
1584more than one flag value. Here we verify that's fixed:
1585
1586 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1587 >>> redundant_flag_value == new_flag_value
1588 True
1589
1590Clean up.
1591 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1592
Tim Petersc6cbab02004-08-22 19:43:28 +00001593 """
1594
Tim Peters8485b562004-08-04 18:46:34 +00001595 def option_directives(): r"""
1596Tests of `DocTestRunner`'s option directive mechanism.
1597
Edward Loper74bca7a2004-08-12 02:27:44 +00001598Option directives can be used to turn option flags on or off for a
1599single example. To turn an option on for an example, follow that
1600example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001601
1602 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001603 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001604 ... [0, 1, ..., 9]
1605 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001606 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001607 ... [0, 1, ..., 9]
1608 ... '''
1609 >>> test = doctest.DocTestFinder().find(f)[0]
1610 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001611 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001612 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001613 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001614 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001615 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001616 Expected:
1617 [0, 1, ..., 9]
1618 Got:
1619 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001620 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001621
1622To turn an option off for an example, follow that example with a
1623comment of the form ``# doctest: -OPTION``:
1624
1625 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001626 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001627 ... [0, 1, ..., 9]
1628 ...
1629 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001630 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001631 ... [0, 1, ..., 9]
1632 ... '''
1633 >>> test = doctest.DocTestFinder().find(f)[0]
1634 >>> doctest.DocTestRunner(verbose=False,
1635 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001636 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001637 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001638 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001639 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001640 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001641 Expected:
1642 [0, 1, ..., 9]
1643 Got:
1644 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001645 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001646
1647Option directives affect only the example that they appear with; they
1648do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001649
Edward Loper74bca7a2004-08-12 02:27:44 +00001650 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001651 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001652 ... [0, 1, ..., 9]
1653 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001654 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001655 ... [0, 1, ..., 9]
1656 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001657 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001658 ... [0, 1, ..., 9]
1659 ... '''
1660 >>> test = doctest.DocTestFinder().find(f)[0]
1661 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001662 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001663 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001664 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001665 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001666 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001667 Expected:
1668 [0, 1, ..., 9]
1669 Got:
1670 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001671 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001672 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001673 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001674 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001675 Expected:
1676 [0, 1, ..., 9]
1677 Got:
1678 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001679 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001680
Edward Loper74bca7a2004-08-12 02:27:44 +00001681Multiple options may be modified by a single option directive. They
1682may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001683
1684 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001685 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001686 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001687 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001688 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001689 ... [0, 1, ..., 9]
1690 ... '''
1691 >>> test = doctest.DocTestFinder().find(f)[0]
1692 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001693 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001694 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001695 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001696 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001697 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001698 Expected:
1699 [0, 1, ..., 9]
1700 Got:
1701 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001702 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001703
1704 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001705 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001706 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001707 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001708 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1709 ... [0, 1, ..., 9]
1710 ... '''
1711 >>> test = doctest.DocTestFinder().find(f)[0]
1712 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001713 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001714 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001715 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001716 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001717 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001718 Expected:
1719 [0, 1, ..., 9]
1720 Got:
1721 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001722 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001723
1724 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001725 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001726 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001727 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001728 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1729 ... [0, 1, ..., 9]
1730 ... '''
1731 >>> test = doctest.DocTestFinder().find(f)[0]
1732 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001733 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001734 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001735 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001736 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001737 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001738 Expected:
1739 [0, 1, ..., 9]
1740 Got:
1741 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001742 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001743
1744The option directive may be put on the line following the source, as
1745long as a continuation prompt is used:
1746
1747 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001748 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001749 ... ... # doctest: +ELLIPSIS
1750 ... [0, 1, ..., 9]
1751 ... '''
1752 >>> test = doctest.DocTestFinder().find(f)[0]
1753 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001754 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001755
Edward Loper74bca7a2004-08-12 02:27:44 +00001756For examples with multi-line source, the option directive may appear
1757at the end of any line:
1758
1759 >>> def f(x): r'''
1760 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001761 ... ... print(' ', x, end='', sep='')
1762 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001763 ...
1764 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001765 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1766 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001767 ... '''
1768 >>> test = doctest.DocTestFinder().find(f)[0]
1769 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001770 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001771
1772If more than one line of an example with multi-line source has an
1773option directive, then they are combined:
1774
1775 >>> def f(x): r'''
1776 ... Should fail (option directive not on the last line):
1777 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001778 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001779 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001780 ... '''
1781 >>> test = doctest.DocTestFinder().find(f)[0]
1782 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001783 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001784
1785It is an error to have a comment of the form ``# doctest:`` that is
1786*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1787``OPTION`` is an option that has been registered with
1788`register_option`:
1789
1790 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001791 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001792 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1793 Traceback (most recent call last):
1794 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1795
1796 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001797 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001798 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1799 Traceback (most recent call last):
1800 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1801
1802It is an error to use an option directive on a line that contains no
1803source:
1804
1805 >>> s = '>>> # doctest: +ELLIPSIS'
1806 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1807 Traceback (most recent call last):
1808 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 +00001809"""
1810
1811def test_testsource(): r"""
1812Unit tests for `testsource()`.
1813
1814The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001815test with that name in that module, and converts it to a script. The
1816example code is converted to regular Python code. The surrounding
1817words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001818
1819 >>> import test.test_doctest
1820 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001821 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001822 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001823 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001824 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001825 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001826 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001827 #
Edward Lopera5db6002004-08-12 02:41:30 +00001828 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001829 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001830
1831 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001832 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001833 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001834 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001835 ## 1
1836 ## 2
1837 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001838 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001839
1840 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001841 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001842 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001843 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001844 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001845 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001846 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001847 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001848 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001849"""
1850
1851def test_debug(): r"""
1852
1853Create a docstring that we want to debug:
1854
1855 >>> s = '''
1856 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001857 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001858 ... 12
1859 ... '''
1860
1861Create some fake stdin input, to feed to the debugger:
1862
Tim Peters8485b562004-08-04 18:46:34 +00001863 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001864 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001865
1866Run the debugger on the docstring, and then restore sys.stdin.
1867
Edward Loper2de91ba2004-08-27 02:07:46 +00001868 >>> try: doctest.debug_src(s)
1869 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001871 (Pdb) next
1872 12
Tim Peters8485b562004-08-04 18:46:34 +00001873 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001875 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001876 12
1877 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001878
1879"""
1880
Brett Cannon31f59292011-02-21 19:29:56 +00001881if not hasattr(sys, 'gettrace') or not sys.gettrace():
1882 def test_pdb_set_trace():
1883 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001884
Brett Cannon31f59292011-02-21 19:29:56 +00001885 You can use pdb.set_trace from a doctest. To do so, you must
1886 retrieve the set_trace function from the pdb module at the time
1887 you use it. The doctest module changes sys.stdout so that it can
1888 capture program output. It also temporarily replaces pdb.set_trace
1889 with a version that restores stdout. This is necessary for you to
1890 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001891
Brett Cannon31f59292011-02-21 19:29:56 +00001892 >>> doc = '''
1893 ... >>> x = 42
1894 ... >>> raise Exception('clé')
1895 ... Traceback (most recent call last):
1896 ... Exception: clé
1897 ... >>> import pdb; pdb.set_trace()
1898 ... '''
1899 >>> parser = doctest.DocTestParser()
1900 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1901 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001902
Brett Cannon31f59292011-02-21 19:29:56 +00001903 To demonstrate this, we'll create a fake standard input that
1904 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001905
Brett Cannon31f59292011-02-21 19:29:56 +00001906 >>> real_stdin = sys.stdin
1907 >>> sys.stdin = _FakeInput([
1908 ... 'print(x)', # print data defined by the example
1909 ... 'continue', # stop debugging
1910 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001911
Brett Cannon31f59292011-02-21 19:29:56 +00001912 >>> try: runner.run(test)
1913 ... finally: sys.stdin = real_stdin
1914 --Return--
1915 > <doctest foo-bar@baz[2]>(1)<module>()->None
1916 -> import pdb; pdb.set_trace()
1917 (Pdb) print(x)
1918 42
1919 (Pdb) continue
1920 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001921
Brett Cannon31f59292011-02-21 19:29:56 +00001922 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001923
Brett Cannon31f59292011-02-21 19:29:56 +00001924 >>> def calls_set_trace():
1925 ... y=2
1926 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001927
Brett Cannon31f59292011-02-21 19:29:56 +00001928 >>> doc = '''
1929 ... >>> x=1
1930 ... >>> calls_set_trace()
1931 ... '''
1932 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1933 >>> real_stdin = sys.stdin
1934 >>> sys.stdin = _FakeInput([
1935 ... 'print(y)', # print data defined in the function
1936 ... 'up', # out of function
1937 ... 'print(x)', # print data defined by the example
1938 ... 'continue', # stop debugging
1939 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001940
Brett Cannon31f59292011-02-21 19:29:56 +00001941 >>> try:
1942 ... runner.run(test)
1943 ... finally:
1944 ... sys.stdin = real_stdin
1945 --Return--
Serhiy Storchakae437a102016-04-24 21:41:02 +03001946 > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
Brett Cannon31f59292011-02-21 19:29:56 +00001947 -> import pdb; pdb.set_trace()
1948 (Pdb) print(y)
1949 2
1950 (Pdb) up
1951 > <doctest foo-bar@baz[1]>(1)<module>()
1952 -> calls_set_trace()
1953 (Pdb) print(x)
1954 1
1955 (Pdb) continue
1956 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001957
Brett Cannon31f59292011-02-21 19:29:56 +00001958 During interactive debugging, source code is shown, even for
1959 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001960
Brett Cannon31f59292011-02-21 19:29:56 +00001961 >>> doc = '''
1962 ... >>> def f(x):
1963 ... ... g(x*2)
1964 ... >>> def g(x):
1965 ... ... print(x+3)
1966 ... ... import pdb; pdb.set_trace()
1967 ... >>> f(3)
1968 ... '''
1969 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1970 >>> real_stdin = sys.stdin
1971 >>> sys.stdin = _FakeInput([
1972 ... 'list', # list source from example 2
1973 ... 'next', # return from g()
1974 ... 'list', # list source from example 1
1975 ... 'next', # return from f()
1976 ... 'list', # list source from example 3
1977 ... 'continue', # stop debugging
1978 ... ''])
1979 >>> try: runner.run(test)
1980 ... finally: sys.stdin = real_stdin
1981 ... # doctest: +NORMALIZE_WHITESPACE
1982 --Return--
1983 > <doctest foo-bar@baz[1]>(3)g()->None
1984 -> import pdb; pdb.set_trace()
1985 (Pdb) list
1986 1 def g(x):
1987 2 print(x+3)
1988 3 -> import pdb; pdb.set_trace()
1989 [EOF]
1990 (Pdb) next
1991 --Return--
1992 > <doctest foo-bar@baz[0]>(2)f()->None
1993 -> g(x*2)
1994 (Pdb) list
1995 1 def f(x):
1996 2 -> g(x*2)
1997 [EOF]
1998 (Pdb) next
1999 --Return--
2000 > <doctest foo-bar@baz[2]>(1)<module>()->None
2001 -> f(3)
2002 (Pdb) list
2003 1 -> f(3)
2004 [EOF]
2005 (Pdb) continue
2006 **********************************************************************
2007 File "foo-bar@baz.py", line 7, in foo-bar@baz
2008 Failed example:
2009 f(3)
2010 Expected nothing
2011 Got:
2012 9
2013 TestResults(failed=1, attempted=3)
2014 """
Jim Fulton356fd192004-08-09 11:34:47 +00002015
Brett Cannon31f59292011-02-21 19:29:56 +00002016 def test_pdb_set_trace_nested():
2017 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00002018
Brett Cannon31f59292011-02-21 19:29:56 +00002019 >>> class C(object):
2020 ... def calls_set_trace(self):
2021 ... y = 1
2022 ... import pdb; pdb.set_trace()
2023 ... self.f1()
2024 ... y = 2
2025 ... def f1(self):
2026 ... x = 1
2027 ... self.f2()
2028 ... x = 2
2029 ... def f2(self):
2030 ... z = 1
2031 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002032
Brett Cannon31f59292011-02-21 19:29:56 +00002033 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002034
Brett Cannon31f59292011-02-21 19:29:56 +00002035 >>> doc = '''
2036 ... >>> a = 1
2037 ... >>> calls_set_trace()
2038 ... '''
2039 >>> parser = doctest.DocTestParser()
2040 >>> runner = doctest.DocTestRunner(verbose=False)
2041 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2042 >>> real_stdin = sys.stdin
2043 >>> sys.stdin = _FakeInput([
2044 ... 'print(y)', # print data defined in the function
2045 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2046 ... 'up', 'print(x)',
2047 ... 'up', 'print(y)',
2048 ... 'up', 'print(foo)',
2049 ... 'continue', # stop debugging
2050 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002051
Brett Cannon31f59292011-02-21 19:29:56 +00002052 >>> try:
2053 ... runner.run(test)
2054 ... finally:
2055 ... sys.stdin = real_stdin
2056 ... # doctest: +REPORT_NDIFF
2057 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2058 -> self.f1()
2059 (Pdb) print(y)
2060 1
2061 (Pdb) step
2062 --Call--
2063 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2064 -> def f1(self):
2065 (Pdb) step
2066 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2067 -> x = 1
2068 (Pdb) step
2069 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2070 -> self.f2()
2071 (Pdb) step
2072 --Call--
2073 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2074 -> def f2(self):
2075 (Pdb) step
2076 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2077 -> z = 1
2078 (Pdb) step
2079 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2080 -> z = 2
2081 (Pdb) print(z)
2082 1
2083 (Pdb) up
2084 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2085 -> self.f2()
2086 (Pdb) print(x)
2087 1
2088 (Pdb) up
2089 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2090 -> self.f1()
2091 (Pdb) print(y)
2092 1
2093 (Pdb) up
2094 > <doctest foo-bar@baz[1]>(1)<module>()
2095 -> calls_set_trace()
2096 (Pdb) print(foo)
2097 *** NameError: name 'foo' is not defined
2098 (Pdb) continue
2099 TestResults(failed=0, attempted=2)
2100 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002101
Tim Peters19397e52004-08-06 22:02:59 +00002102def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002103 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002104
2105 We create a Suite by providing a module. A module can be provided
2106 by passing a module object:
2107
2108 >>> import unittest
2109 >>> import test.sample_doctest
2110 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2111 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002112 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002113
2114 We can also supply the module by name:
2115
2116 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2117 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002118 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002119
R David Murray5abd76a2012-09-10 10:15:58 -04002120 The module need not contain any doctest examples:
2121
2122 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2123 >>> suite.run(unittest.TestResult())
2124 <unittest.result.TestResult run=0 errors=0 failures=0>
2125
R David Murray1976d9b2014-04-14 20:28:36 -04002126 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002127
R David Murray1976d9b2014-04-14 20:28:36 -04002128 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002129 >>> suite.run(unittest.TestResult())
2130 <unittest.result.TestResult run=0 errors=0 failures=0>
2131
Tim Peters19397e52004-08-06 22:02:59 +00002132 We can use the current module:
2133
2134 >>> suite = test.sample_doctest.test_suite()
2135 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002136 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002137
R David Murray1976d9b2014-04-14 20:28:36 -04002138 We can also provide a DocTestFinder:
2139
2140 >>> finder = doctest.DocTestFinder()
2141 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2142 ... test_finder=finder)
2143 >>> suite.run(unittest.TestResult())
2144 <unittest.result.TestResult run=9 errors=0 failures=4>
2145
2146 The DocTestFinder need not return any tests:
2147
2148 >>> finder = doctest.DocTestFinder()
2149 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2150 ... test_finder=finder)
2151 >>> suite.run(unittest.TestResult())
2152 <unittest.result.TestResult run=0 errors=0 failures=0>
2153
Tim Peters19397e52004-08-06 22:02:59 +00002154 We can supply global variables. If we pass globs, they will be
2155 used instead of the module globals. Here we'll pass an empty
2156 globals, triggering an extra error:
2157
2158 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2159 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002160 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002161
2162 Alternatively, we can provide extra globals. Here we'll make an
2163 error go away by providing an extra global variable:
2164
2165 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2166 ... extraglobs={'y': 1})
2167 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002168 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002169
2170 You can pass option flags. Here we'll cause an extra error
2171 by disabling the blank-line feature:
2172
2173 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002174 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002175 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002176 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002177
Tim Peters1e277ee2004-08-07 05:37:52 +00002178 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002179
Jim Fultonf54bad42004-08-28 14:57:56 +00002180 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002181 ... import test.test_doctest
2182 ... test.test_doctest.sillySetup = True
2183
Jim Fultonf54bad42004-08-28 14:57:56 +00002184 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002185 ... import test.test_doctest
2186 ... del test.test_doctest.sillySetup
2187
2188 Here, we installed a silly variable that the test expects:
2189
2190 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2191 ... setUp=setUp, tearDown=tearDown)
2192 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002193 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002194
2195 But the tearDown restores sanity:
2196
2197 >>> import test.test_doctest
2198 >>> test.test_doctest.sillySetup
2199 Traceback (most recent call last):
2200 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002201 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002202
Berker Peksag4882cac2015-04-14 09:30:01 +03002203 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002204 we'll use the setUp function to supply the missing variable y:
2205
2206 >>> def setUp(test):
2207 ... test.globs['y'] = 1
2208
2209 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2210 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002211 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002212
2213 Here, we didn't need to use a tearDown function because we
2214 modified the test globals, which are a copy of the
2215 sample_doctest module dictionary. The test globals are
2216 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002217 """
2218
2219def test_DocFileSuite():
2220 """We can test tests found in text files using a DocFileSuite.
2221
2222 We create a suite by providing the names of one or more text
2223 files that include examples:
2224
2225 >>> import unittest
2226 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002227 ... 'test_doctest2.txt',
2228 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002229 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002230 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002231
2232 The test files are looked for in the directory containing the
2233 calling module. A package keyword argument can be provided to
2234 specify a different relative location.
2235
2236 >>> import unittest
2237 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2238 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002239 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002240 ... package='test')
2241 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002242 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002243
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002244 Support for using a package's __loader__.get_data() is also
2245 provided.
2246
2247 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002248 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002249 >>> if not hasattr(test, '__loader__'):
2250 ... test.__loader__ = pkgutil.get_loader(test)
2251 ... added_loader = True
2252 >>> try:
2253 ... suite = doctest.DocFileSuite('test_doctest.txt',
2254 ... 'test_doctest2.txt',
2255 ... 'test_doctest4.txt',
2256 ... package='test')
2257 ... suite.run(unittest.TestResult())
2258 ... finally:
2259 ... if added_loader:
2260 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002261 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002262
Edward Loper0273f5b2004-09-18 20:27:04 +00002263 '/' should be used as a path separator. It will be converted
2264 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002265
2266 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2267 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002268 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002269
Edward Loper0273f5b2004-09-18 20:27:04 +00002270 If DocFileSuite is used from an interactive session, then files
2271 are resolved relative to the directory of sys.argv[0]:
2272
Christian Heimes45f9af32007-11-27 21:50:00 +00002273 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002274 >>> save_argv = sys.argv
2275 >>> sys.argv = [test.test_doctest.__file__]
2276 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002277 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002278 >>> sys.argv = save_argv
2279
Edward Loper052d0cd2004-09-19 17:19:33 +00002280 By setting `module_relative=False`, os-specific paths may be
2281 used (including absolute paths and paths relative to the
2282 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002283
2284 >>> # Get the absolute path of the test package.
2285 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2286 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2287
2288 >>> # Use it to find the absolute path of test_doctest.txt.
2289 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2290
Edward Loper052d0cd2004-09-19 17:19:33 +00002291 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002292 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002293 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002294
Edward Loper052d0cd2004-09-19 17:19:33 +00002295 It is an error to specify `package` when `module_relative=False`:
2296
2297 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2298 ... package='test')
2299 Traceback (most recent call last):
2300 ValueError: Package may only be specified for module-relative paths.
2301
Tim Peters19397e52004-08-06 22:02:59 +00002302 You can specify initial global variables:
2303
2304 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2305 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002306 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002307 ... globs={'favorite_color': 'blue'})
2308 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002309 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002310
2311 In this case, we supplied a missing favorite color. You can
2312 provide doctest options:
2313
2314 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2315 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002316 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002317 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2318 ... globs={'favorite_color': 'blue'})
2319 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002320 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002321
2322 And, you can provide setUp and tearDown functions:
2323
Jim Fultonf54bad42004-08-28 14:57:56 +00002324 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002325 ... import test.test_doctest
2326 ... test.test_doctest.sillySetup = True
2327
Jim Fultonf54bad42004-08-28 14:57:56 +00002328 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002329 ... import test.test_doctest
2330 ... del test.test_doctest.sillySetup
2331
2332 Here, we installed a silly variable that the test expects:
2333
2334 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2335 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002336 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002337 ... setUp=setUp, tearDown=tearDown)
2338 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002339 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002340
2341 But the tearDown restores sanity:
2342
2343 >>> import test.test_doctest
2344 >>> test.test_doctest.sillySetup
2345 Traceback (most recent call last):
2346 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002347 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002348
Berker Peksag4882cac2015-04-14 09:30:01 +03002349 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002350 Here, we'll use a setUp function to set the favorite color in
2351 test_doctest.txt:
2352
2353 >>> def setUp(test):
2354 ... test.globs['favorite_color'] = 'blue'
2355
2356 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2357 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002358 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002359
2360 Here, we didn't need to use a tearDown function because we
2361 modified the test globals. The test globals are
2362 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002363
Fred Drake7c404a42004-12-21 23:46:34 +00002364 Tests in a file run using `DocFileSuite` can also access the
2365 `__file__` global, which is set to the name of the file
2366 containing the tests:
2367
Benjamin Petersonab078e92016-07-13 21:13:29 -07002368 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
Fred Drake7c404a42004-12-21 23:46:34 +00002369 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002370 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002371
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002372 If the tests contain non-ASCII characters, we have to specify which
2373 encoding the file is encoded with. We do so by using the `encoding`
2374 parameter:
2375
2376 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2377 ... 'test_doctest2.txt',
2378 ... 'test_doctest4.txt',
2379 ... encoding='utf-8')
2380 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002381 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002382
Jim Fultonf54bad42004-08-28 14:57:56 +00002383 """
Tim Peters19397e52004-08-06 22:02:59 +00002384
Jim Fulton07a349c2004-08-22 14:10:00 +00002385def test_trailing_space_in_test():
2386 """
Tim Petersa7def722004-08-23 22:13:22 +00002387 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002388
Jim Fulton07a349c2004-08-22 14:10:00 +00002389 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002390 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002391 foo \n
2392 """
Tim Peters19397e52004-08-06 22:02:59 +00002393
Yury Selivanovb532df62014-12-08 15:00:05 -05002394class Wrapper:
2395 def __init__(self, func):
2396 self.func = func
2397 functools.update_wrapper(self, func)
2398
2399 def __call__(self, *args, **kwargs):
2400 self.func(*args, **kwargs)
2401
2402@Wrapper
2403def test_look_in_unwrapped():
2404 """
2405 Docstrings in wrapped functions must be detected as well.
2406
2407 >>> 'one other test'
2408 'one other test'
2409 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002410
2411def test_unittest_reportflags():
2412 """Default unittest reporting flags can be set to control reporting
2413
2414 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2415 only the first failure of each test. First, we'll look at the
2416 output without the flag. The file test_doctest.txt file has two
2417 tests. They both fail if blank lines are disabled:
2418
2419 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2420 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2421 >>> import unittest
2422 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002423 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002424 Traceback ...
2425 Failed example:
2426 favorite_color
2427 ...
2428 Failed example:
2429 if 1:
2430 ...
2431
2432 Note that we see both failures displayed.
2433
2434 >>> old = doctest.set_unittest_reportflags(
2435 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2436
2437 Now, when we run the test:
2438
2439 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002440 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002441 Traceback ...
2442 Failed example:
2443 favorite_color
2444 Exception raised:
2445 ...
2446 NameError: name 'favorite_color' is not defined
2447 <BLANKLINE>
2448 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002449
Jim Fultonf54bad42004-08-28 14:57:56 +00002450 We get only the first failure.
2451
2452 If we give any reporting options when we set up the tests,
2453 however:
2454
2455 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2456 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2457
2458 Then the default eporting options are ignored:
2459
2460 >>> result = suite.run(unittest.TestResult())
Pablo Galindoc5dc60e2019-01-10 14:29:40 +00002461
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302462 *NOTE*: These doctest are intentionally not placed in raw string to depict
2463 the trailing whitespace using `\x20` in the diff below.
2464
Guido van Rossum7131f842007-02-09 20:13:25 +00002465 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002466 Traceback ...
2467 Failed example:
2468 favorite_color
2469 ...
2470 Failed example:
2471 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002472 print('a')
2473 print()
2474 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002475 Differences (ndiff with -expected +actual):
2476 a
2477 - <BLANKLINE>
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302478 +\x20
Jim Fultonf54bad42004-08-28 14:57:56 +00002479 b
2480 <BLANKLINE>
2481 <BLANKLINE>
2482
2483
2484 Test runners can restore the formatting flags after they run:
2485
2486 >>> ignored = doctest.set_unittest_reportflags(old)
2487
2488 """
2489
Edward Loper052d0cd2004-09-19 17:19:33 +00002490def test_testfile(): r"""
2491Tests for the `testfile()` function. This function runs all the
Min ho Kimc4cacc82019-07-31 08:16:13 +10002492doctest examples in a given file. In its simple invocation, it is
Edward Loper052d0cd2004-09-19 17:19:33 +00002493called with the name of a file, which is taken to be relative to the
2494calling module. The return value is (#failures, #tests).
2495
Florent Xicluna59250852010-02-27 14:21:57 +00002496We don't want `-v` in sys.argv for these tests.
2497
2498 >>> save_argv = sys.argv
2499 >>> if '-v' in sys.argv:
2500 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2501
2502
Edward Loper052d0cd2004-09-19 17:19:33 +00002503 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2504 **********************************************************************
2505 File "...", line 6, in test_doctest.txt
2506 Failed example:
2507 favorite_color
2508 Exception raised:
2509 ...
2510 NameError: name 'favorite_color' is not defined
2511 **********************************************************************
2512 1 items had failures:
2513 1 of 2 in test_doctest.txt
2514 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002515 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002516 >>> doctest.master = None # Reset master.
2517
2518(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002519`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002520same name.)
2521
2522Globals may be specified with the `globs` and `extraglobs` parameters:
2523
2524 >>> globs = {'favorite_color': 'blue'}
2525 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002526 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002527 >>> doctest.master = None # Reset master.
2528
2529 >>> extraglobs = {'favorite_color': 'red'}
2530 >>> doctest.testfile('test_doctest.txt', globs=globs,
2531 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2532 **********************************************************************
2533 File "...", line 6, in test_doctest.txt
2534 Failed example:
2535 favorite_color
2536 Expected:
2537 'blue'
2538 Got:
2539 'red'
2540 **********************************************************************
2541 1 items had failures:
2542 1 of 2 in test_doctest.txt
2543 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002544 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002545 >>> doctest.master = None # Reset master.
2546
2547The file may be made relative to a given module or package, using the
2548optional `module_relative` parameter:
2549
2550 >>> doctest.testfile('test_doctest.txt', globs=globs,
2551 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002552 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002553 >>> doctest.master = None # Reset master.
2554
Ezio Melotti13925002011-03-16 11:05:33 +02002555Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002556
2557 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2558 Trying:
2559 favorite_color
2560 Expecting:
2561 'blue'
2562 ok
2563 Trying:
2564 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002565 print('a')
2566 print()
2567 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002568 Expecting:
2569 a
2570 <BLANKLINE>
2571 b
2572 ok
2573 1 items passed all tests:
2574 2 tests in test_doctest.txt
2575 2 tests in 1 items.
2576 2 passed and 0 failed.
2577 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002578 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002579 >>> doctest.master = None # Reset master.
2580
2581The name of the test may be specified with the optional `name`
2582parameter:
2583
2584 >>> doctest.testfile('test_doctest.txt', name='newname')
2585 ... # doctest: +ELLIPSIS
2586 **********************************************************************
2587 File "...", line 6, in newname
2588 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002589 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002590 >>> doctest.master = None # Reset master.
2591
Ezio Melotti13925002011-03-16 11:05:33 +02002592The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002593parameter:
2594
2595 >>> doctest.testfile('test_doctest.txt', report=False)
2596 ... # doctest: +ELLIPSIS
2597 **********************************************************************
2598 File "...", line 6, in test_doctest.txt
2599 Failed example:
2600 favorite_color
2601 Exception raised:
2602 ...
2603 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002604 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002605 >>> doctest.master = None # Reset master.
2606
2607The optional keyword argument `raise_on_error` can be used to raise an
2608exception on the first error (which may be useful for postmortem
2609debugging):
2610
2611 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2612 ... # doctest: +ELLIPSIS
2613 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002614 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002615 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002616
2617If the tests contain non-ASCII characters, the tests might fail, since
2618it's unknown which encoding is used. The encoding can be specified
2619using the optional keyword argument `encoding`:
2620
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002621 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002622 **********************************************************************
2623 File "...", line 7, in test_doctest4.txt
2624 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002625 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002626 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002627 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002628 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002629 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002630 **********************************************************************
2631 ...
2632 **********************************************************************
2633 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002634 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002635 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002636 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002637 >>> doctest.master = None # Reset master.
2638
2639 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002640 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002641 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002642
2643Test the verbose output:
2644
2645 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2646 Trying:
2647 'föö'
2648 Expecting:
2649 'f\xf6\xf6'
2650 ok
2651 Trying:
2652 'bÄ…r'
2653 Expecting:
2654 'b\u0105r'
2655 ok
2656 1 items passed all tests:
2657 2 tests in test_doctest4.txt
2658 2 tests in 1 items.
2659 2 passed and 0 failed.
2660 Test passed.
2661 TestResults(failed=0, attempted=2)
2662 >>> doctest.master = None # Reset master.
2663 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002664"""
2665
R David Murrayb48cb292014-10-02 22:42:42 -04002666def test_lineendings(): r"""
2667*nix systems use \n line endings, while Windows systems use \r\n. Python
2668handles this using universal newline mode for reading files. Let's make
2669sure doctest does so (issue 8473) by creating temporary test files using each
2670of the two line disciplines. One of the two will be the "wrong" one for the
2671platform the test is run on.
2672
2673Windows line endings first:
2674
2675 >>> import tempfile, os
2676 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002677 >>> with open(fn, 'wb') as f:
2678 ... 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 -04002679 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002680 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002681 TestResults(failed=0, attempted=1)
2682 >>> os.remove(fn)
2683
2684And now *nix line endings:
2685
2686 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002687 >>> with open(fn, 'wb') as f:
2688 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002689 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002690 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002691 TestResults(failed=0, attempted=1)
2692 >>> os.remove(fn)
2693
2694"""
2695
R. David Murray58641de2009-06-12 15:33:19 +00002696def test_testmod(): r"""
2697Tests for the testmod function. More might be useful, but for now we're just
2698testing the case raised by Issue 6195, where trying to doctest a C module would
2699fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2700out of the binary module.
2701
2702 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002703 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002704 TestResults(failed=0, attempted=0)
2705"""
2706
Victor Stinner9d396392010-10-16 21:54:59 +00002707try:
2708 os.fsencode("foo-bär@baz.py")
2709except UnicodeEncodeError:
2710 # Skip the test: the filesystem encoding is unable to encode the filename
2711 pass
2712else:
2713 def test_unicode(): """
2714Check doctest with a non-ascii filename:
2715
2716 >>> doc = '''
2717 ... >>> raise Exception('clé')
2718 ... '''
2719 ...
2720 >>> parser = doctest.DocTestParser()
2721 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2722 >>> test
2723 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2724 >>> runner = doctest.DocTestRunner(verbose=False)
2725 >>> runner.run(test) # doctest: +ELLIPSIS
2726 **********************************************************************
2727 File "foo-bär@baz.py", line 2, in foo-bär@baz
2728 Failed example:
2729 raise Exception('clé')
2730 Exception raised:
2731 Traceback (most recent call last):
2732 File ...
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03002733 exec(compile(example.source, filename, "single",
Victor Stinner9d396392010-10-16 21:54:59 +00002734 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2735 raise Exception('clé')
2736 Exception: clé
2737 TestResults(failed=1, attempted=1)
2738 """
2739
R David Murray5707d502013-06-23 14:24:13 -04002740def test_CLI(): r"""
2741The doctest module can be used to run doctests against an arbitrary file.
2742These tests test this CLI functionality.
2743
2744We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002745to a temp dir to run the command against. Due to a current limitation in
2746script_helpers, though, we need a little utility function to turn the returned
2747output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002748
R David Murray4af68982013-06-25 08:11:22 -04002749 >>> def normalize(s):
2750 ... return '\n'.join(s.decode().splitlines())
2751
R David Murray4af68982013-06-25 08:11:22 -04002752With those preliminaries out of the way, we'll start with a file with two
2753simple tests and no errors. We'll run both the unadorned doctest command, and
2754the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002755
Berker Peksagce643912015-05-06 06:33:17 +03002756 >>> from test.support import script_helper, temp_dir
2757 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002758 ... fn = os.path.join(tmpdir, 'myfile.doc')
2759 ... with open(fn, 'w') as f:
2760 ... _ = f.write('This is a very simple test file.\n')
2761 ... _ = f.write(' >>> 1 + 1\n')
2762 ... _ = f.write(' 2\n')
2763 ... _ = f.write(' >>> "a"\n')
2764 ... _ = f.write(" 'a'\n")
2765 ... _ = f.write('\n')
2766 ... _ = f.write('And that is it.\n')
2767 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002768 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002769 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002770 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002771
2772With no arguments and passing tests, we should get no output:
2773
2774 >>> rc1, out1, err1
2775 (0, b'', b'')
2776
2777With the verbose flag, we should see the test output, but no error output:
2778
2779 >>> rc2, err2
2780 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002781 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002782 Trying:
2783 1 + 1
2784 Expecting:
2785 2
2786 ok
2787 Trying:
2788 "a"
2789 Expecting:
2790 'a'
2791 ok
2792 1 items passed all tests:
2793 2 tests in myfile.doc
2794 2 tests in 1 items.
2795 2 passed and 0 failed.
2796 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002797
2798Now we'll write a couple files, one with three tests, the other a python module
2799with two tests, both of the files having "errors" in the tests that can be made
2800non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2801the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002802allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002803ability to process more than one file on the command line and, since the second
2804file ends in '.py', its handling of python module files (as opposed to straight
2805text files).
2806
Berker Peksagce643912015-05-06 06:33:17 +03002807 >>> from test.support import script_helper, temp_dir
2808 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002809 ... fn = os.path.join(tmpdir, 'myfile.doc')
2810 ... with open(fn, 'w') as f:
2811 ... _ = f.write('This is another simple test file.\n')
2812 ... _ = f.write(' >>> 1 + 1\n')
2813 ... _ = f.write(' 2\n')
2814 ... _ = f.write(' >>> "abcdef"\n')
2815 ... _ = f.write(" 'a...f'\n")
2816 ... _ = f.write(' >>> "ajkml"\n')
2817 ... _ = f.write(" 'a...l'\n")
2818 ... _ = f.write('\n')
2819 ... _ = f.write('And that is it.\n')
2820 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2821 ... with open(fn2, 'w') as f:
2822 ... _ = f.write('def test_func():\n')
2823 ... _ = f.write(' \"\"\"\n')
2824 ... _ = f.write(' This is simple python test function.\n')
2825 ... _ = f.write(' >>> 1 + 1\n')
2826 ... _ = f.write(' 2\n')
2827 ... _ = f.write(' >>> "abc def"\n')
2828 ... _ = f.write(" 'abc def'\n")
2829 ... _ = f.write("\n")
2830 ... _ = f.write(' \"\"\"\n')
R David Murray5707d502013-06-23 14:24:13 -04002831 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002832 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002833 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002834 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002835 ... rc3, out3, err3 = script_helper.assert_python_ok(
2836 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002837 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002838 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002839 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002840 ... rc5, out5, err5 = script_helper.assert_python_ok(
2841 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002842 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002843
2844Our first test run will show the errors from the first file (doctest stops if a
2845file has errors). Note that doctest test-run error output appears on stdout,
2846not stderr:
2847
2848 >>> rc1, err1
2849 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002850 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002851 **********************************************************************
2852 File "...myfile.doc", line 4, in myfile.doc
2853 Failed example:
2854 "abcdef"
2855 Expected:
2856 'a...f'
2857 Got:
2858 'abcdef'
2859 **********************************************************************
2860 File "...myfile.doc", line 6, in myfile.doc
2861 Failed example:
2862 "ajkml"
2863 Expected:
2864 'a...l'
2865 Got:
2866 'ajkml'
2867 **********************************************************************
2868 1 items had failures:
2869 2 of 3 in myfile.doc
2870 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002871
2872With -o ELLIPSIS specified, the second run, against just the first file, should
2873produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2874should the third, which ran against both files:
2875
2876 >>> rc2, out2, err2
2877 (0, b'', b'')
2878 >>> rc3, out3, err3
2879 (0, b'', b'')
2880
2881The fourth run uses FAIL_FAST, so we should see only one error:
2882
2883 >>> rc4, err4
2884 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002885 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002886 **********************************************************************
2887 File "...myfile.doc", line 4, in myfile.doc
2888 Failed example:
2889 "abcdef"
2890 Expected:
2891 'a...f'
2892 Got:
2893 'abcdef'
2894 **********************************************************************
2895 1 items had failures:
2896 1 of 2 in myfile.doc
2897 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002898
2899The fifth test uses verbose with the two options, so we should get verbose
2900success output for the tests in both files:
2901
2902 >>> rc5, err5
2903 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002904 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002905 Trying:
2906 1 + 1
2907 Expecting:
2908 2
2909 ok
2910 Trying:
2911 "abcdef"
2912 Expecting:
2913 'a...f'
2914 ok
2915 Trying:
2916 "ajkml"
2917 Expecting:
2918 'a...l'
2919 ok
2920 1 items passed all tests:
2921 3 tests in myfile.doc
2922 3 tests in 1 items.
2923 3 passed and 0 failed.
2924 Test passed.
2925 Trying:
2926 1 + 1
2927 Expecting:
2928 2
2929 ok
2930 Trying:
2931 "abc def"
2932 Expecting:
2933 'abc def'
2934 ok
2935 1 items had no tests:
2936 myfile2
2937 1 items passed all tests:
2938 2 tests in myfile2.test_func
2939 2 tests in 2 items.
2940 2 passed and 0 failed.
2941 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002942
2943We should also check some typical error cases.
2944
2945Invalid file name:
2946
2947 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002948 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04002949 >>> rc, out
2950 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002951 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002952 Traceback (most recent call last):
2953 ...
2954 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
2955
2956Invalid doctest option:
2957
2958 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002959 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04002960 >>> rc, out
2961 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04002962 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002963 usage...invalid...nosuchoption...
2964
2965"""
2966
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302967def test_no_trailing_whitespace_stripping():
2968 r"""
2969 The fancy reports had a bug for a long time where any trailing whitespace on
2970 the reported diff lines was stripped, making it impossible to see the
2971 differences in line reported as different that differed only in the amount of
2972 trailing whitespace. The whitespace still isn't particularly visible unless
2973 you use NDIFF, but at least it is now there to be found.
2974
2975 *NOTE*: This snippet was intentionally put inside a raw string to get rid of
2976 leading whitespace error in executing the example below
2977
2978 >>> def f(x):
2979 ... r'''
2980 ... >>> print('\n'.join(['a ', 'b']))
2981 ... a
2982 ... b
2983 ... '''
2984 """
2985 """
2986 *NOTE*: These doctest are not placed in raw string to depict the trailing whitespace
2987 using `\x20`
2988
2989 >>> test = doctest.DocTestFinder().find(f)[0]
2990 >>> flags = doctest.REPORT_NDIFF
2991 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
2992 ... # doctest: +ELLIPSIS
2993 **********************************************************************
2994 File ..., line 3, in f
2995 Failed example:
2996 print('\n'.join(['a ', 'b']))
2997 Differences (ndiff with -expected +actual):
2998 - a
2999 + a
3000 b
3001 TestResults(failed=1, attempted=1)
3002
3003 *NOTE*: `\x20` is for checking the trailing whitespace on the +a line above.
3004 We cannot use actual spaces there, as a commit hook prevents from committing
3005 patches that contain trailing whitespace. More info on Issue 24746.
3006 """
3007
Tim Peters8485b562004-08-04 18:46:34 +00003008######################################################################
3009## Main
3010######################################################################
3011
3012def test_main():
3013 # Check the doctest cases in doctest itself:
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02003014 ret = support.run_doctest(doctest, verbosity=True)
Victor Stinner931602a2016-03-25 12:48:17 +01003015
Tim Peters8485b562004-08-04 18:46:34 +00003016 # Check the doctest cases defined here:
3017 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003018 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00003019
Jason R. Coombsb9650a02018-03-05 18:29:08 -05003020 # Run unittests
3021 support.run_unittest(__name__)
3022
3023
Tim Peters8485b562004-08-04 18:46:34 +00003024def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00003025 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01003026 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00003027 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00003028 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00003029 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003030 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00003031 r.write_results(show_missing=True, summary=True,
3032 coverdir=coverdir)
3033
3034if __name__ == '__main__':
3035 if '-c' in sys.argv:
3036 test_coverage('/tmp/doctest.cover')
3037 else:
3038 test_main()