blob: bff20f9cac9c989f17f3b701abd2346ac6526a39 [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
Hai Shi46605972020-08-04 00:49:18 +08006from test.support import import_helper
7from test.support import os_helper
Tim Peters8485b562004-08-04 18:46:34 +00008import doctest
Yury Selivanovb532df62014-12-08 15:00:05 -05009import functools
Victor Stinner9d396392010-10-16 21:54:59 +000010import os
Brett Cannon31f59292011-02-21 19:29:56 +000011import sys
Jason R. Coombsb9650a02018-03-05 18:29:08 -050012import importlib
Peter Donise0b81012020-03-26 11:53:16 -040013import importlib.abc
14import importlib.util
Jason R. Coombsb9650a02018-03-05 18:29:08 -050015import unittest
Nick Coghland5d9e022018-03-25 23:03:10 +100016import tempfile
Peter Donise0b81012020-03-26 11:53:16 -040017import shutil
18import contextlib
Florent Xiclunadc6f2d02010-04-02 19:25:32 +000019
Nick Coghlanf088e5e2008-12-14 11:50:48 +000020# NOTE: There are some additional tests relating to interaction with
21# zipimport in the test_zipimport_support test module.
22
Tim Peters8485b562004-08-04 18:46:34 +000023######################################################################
24## Sample Objects (used by test cases)
25######################################################################
26
27def sample_func(v):
28 """
Tim Peters19397e52004-08-06 22:02:59 +000029 Blah blah
30
Guido van Rossum7131f842007-02-09 20:13:25 +000031 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000032 44
Tim Peters19397e52004-08-06 22:02:59 +000033
34 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000035 """
36 return v+v
37
38class SampleClass:
39 """
Guido van Rossum7131f842007-02-09 20:13:25 +000040 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000041 1
Edward Loper4ae900f2004-09-21 03:20:34 +000042
43 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
44 >>>
45 ...
46
47 Multiline example:
48 >>> sc = SampleClass(3)
49 >>> for i in range(10):
50 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000051 ... print(' ', sc.get(), sep='', end='')
52 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000053 """
54 def __init__(self, val):
55 """
Guido van Rossum7131f842007-02-09 20:13:25 +000056 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000057 12
58 """
59 self.val = val
60
61 def double(self):
62 """
Guido van Rossum7131f842007-02-09 20:13:25 +000063 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000064 24
65 """
66 return SampleClass(self.val + self.val)
67
68 def get(self):
69 """
Guido van Rossum7131f842007-02-09 20:13:25 +000070 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000071 -5
72 """
73 return self.val
74
75 def a_staticmethod(v):
76 """
Guido van Rossum7131f842007-02-09 20:13:25 +000077 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000078 11
79 """
80 return v+1
81 a_staticmethod = staticmethod(a_staticmethod)
82
83 def a_classmethod(cls, v):
84 """
Guido van Rossum7131f842007-02-09 20:13:25 +000085 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000086 12
Guido van Rossum7131f842007-02-09 20:13:25 +000087 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000088 12
89 """
90 return v+2
91 a_classmethod = classmethod(a_classmethod)
92
93 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000094 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000095 22
96 """)
97
98 class NestedClass:
99 """
100 >>> x = SampleClass.NestedClass(5)
101 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +0000102 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +0000103 25
104 """
105 def __init__(self, val=0):
106 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000107 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +0000108 0
109 """
110 self.val = val
111 def square(self):
112 return SampleClass.NestedClass(self.val*self.val)
113 def get(self):
114 return self.val
115
116class SampleNewStyleClass(object):
117 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000118 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000119 1
120 2
121 3
122 """
123 def __init__(self, val):
124 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000125 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000126 12
127 """
128 self.val = val
129
130 def double(self):
131 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000132 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000133 24
134 """
135 return SampleNewStyleClass(self.val + self.val)
136
137 def get(self):
138 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000139 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000140 -5
141 """
142 return self.val
143
144######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000145## Fake stdin (for testing interactive debugging)
146######################################################################
147
148class _FakeInput:
149 """
150 A fake input stream for pdb's interactive debugger. Whenever a
151 line is read, print it (to simulate the user typing it), and then
152 return it. The set of lines to return is specified in the
153 constructor; they should not have trailing newlines.
154 """
155 def __init__(self, lines):
156 self.lines = lines
157
158 def readline(self):
159 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000160 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000161 return line+'\n'
162
163######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000164## Test Cases
165######################################################################
166
167def test_Example(): r"""
168Unit tests for the `Example` class.
169
Edward Lopera6b68322004-08-26 00:05:43 +0000170Example is a simple container class that holds:
171 - `source`: A source string.
172 - `want`: An expected output string.
173 - `exc_msg`: An expected exception message string (or None if no
174 exception is expected).
175 - `lineno`: A line number (within the docstring).
176 - `indent`: The example's indentation in the input string.
177 - `options`: An option dictionary, mapping option flags to True or
178 False.
Tim Peters8485b562004-08-04 18:46:34 +0000179
Edward Lopera6b68322004-08-26 00:05:43 +0000180These attributes are set by the constructor. `source` and `want` are
181required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000182
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000183 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000184 >>> (example.source, example.want, example.exc_msg,
185 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000186 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000187
188The first three attributes (`source`, `want`, and `exc_msg`) may be
189specified positionally; the remaining arguments should be specified as
190keyword arguments:
191
192 >>> exc_msg = 'IndexError: pop from an empty list'
193 >>> example = doctest.Example('[].pop()', '', exc_msg,
194 ... lineno=5, indent=4,
195 ... options={doctest.ELLIPSIS: True})
196 >>> (example.source, example.want, example.exc_msg,
197 ... example.lineno, example.indent, example.options)
198 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
199
200The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000201
Tim Petersbb431472004-08-09 03:51:46 +0000202 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000203 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000204 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000205 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000206
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000207 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000208 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000209 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000210
Tim Petersbb431472004-08-09 03:51:46 +0000211 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000212 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000213 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000214 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000215
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000216 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000217 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000218 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000219
Edward Lopera6b68322004-08-26 00:05:43 +0000220 Empty source string (which should never appear in real examples)
221 >>> e = doctest.Example('', '')
222 >>> e.source, e.want
223 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000224
Edward Lopera6b68322004-08-26 00:05:43 +0000225The constructor normalizes the `want` string to end in a newline,
226unless it's the empty string:
227
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000228 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000229 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000230 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000231
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000232 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000233 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000234 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000235
Edward Lopera6b68322004-08-26 00:05:43 +0000236 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000237 >>> e.source, e.want
238 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000239
240The constructor normalizes the `exc_msg` string to end in a newline,
241unless it's `None`:
242
243 Message spans one line
244 >>> exc_msg = 'IndexError: pop from an empty list'
245 >>> e = doctest.Example('[].pop()', '', exc_msg)
246 >>> e.exc_msg
247 'IndexError: pop from an empty list\n'
248
249 >>> exc_msg = 'IndexError: pop from an empty list\n'
250 >>> e = doctest.Example('[].pop()', '', exc_msg)
251 >>> e.exc_msg
252 'IndexError: pop from an empty list\n'
253
254 Message spans multiple lines
255 >>> exc_msg = 'ValueError: 1\n 2'
256 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
257 >>> e.exc_msg
258 'ValueError: 1\n 2\n'
259
260 >>> exc_msg = 'ValueError: 1\n 2\n'
261 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
262 >>> e.exc_msg
263 'ValueError: 1\n 2\n'
264
265 Empty (but non-None) exception message (which should never appear
266 in real examples)
267 >>> exc_msg = ''
268 >>> e = doctest.Example('raise X()', '', exc_msg)
269 >>> e.exc_msg
270 '\n'
Antoine Pitrou165b1282011-12-18 20:20:17 +0100271
272Compare `Example`:
273 >>> example = doctest.Example('print 1', '1\n')
274 >>> same_example = doctest.Example('print 1', '1\n')
275 >>> other_example = doctest.Example('print 42', '42\n')
276 >>> example == same_example
277 True
278 >>> example != same_example
279 False
280 >>> hash(example) == hash(same_example)
281 True
282 >>> example == other_example
283 False
284 >>> example != other_example
285 True
Tim Peters8485b562004-08-04 18:46:34 +0000286"""
287
288def test_DocTest(): r"""
289Unit tests for the `DocTest` class.
290
291DocTest is a collection of examples, extracted from a docstring, along
292with information about where the docstring comes from (a name,
293filename, and line number). The docstring is parsed by the `DocTest`
294constructor:
295
296 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000297 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000298 ... 12
299 ...
300 ... Non-example text.
301 ...
R David Murray44b548d2016-09-08 13:59:53 -0400302 ... >>> print('another\\example')
Tim Peters8485b562004-08-04 18:46:34 +0000303 ... another
304 ... example
305 ... '''
306 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000307 >>> parser = doctest.DocTestParser()
308 >>> test = parser.get_doctest(docstring, globs, 'some_test',
309 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000310 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000311 <DocTest some_test from some_file:20 (2 examples)>
312 >>> len(test.examples)
313 2
314 >>> e1, e2 = test.examples
315 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000316 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000317 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000318 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000319
320Source information (name, filename, and line number) is available as
321attributes on the doctest object:
322
323 >>> (test.name, test.filename, test.lineno)
324 ('some_test', 'some_file', 20)
325
326The line number of an example within its containing file is found by
327adding the line number of the example and the line number of its
328containing test:
329
330 >>> test.lineno + e1.lineno
331 21
332 >>> test.lineno + e2.lineno
333 26
334
Martin Panter46f50722016-05-26 05:35:26 +0000335If the docstring contains inconsistent leading whitespace in the
Tim Peters8485b562004-08-04 18:46:34 +0000336expected output of an example, then `DocTest` will raise a ValueError:
337
338 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000339 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000340 ... bad
341 ... indentation
342 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000343 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000344 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000345 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000346
347If the docstring contains inconsistent leading whitespace on
348continuation lines, then `DocTest` will raise a ValueError:
349
350 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000351 ... >>> print(('bad indentation',
352 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000353 ... ('bad', 'indentation')
354 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000355 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000356 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000357 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000358
359If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
360will raise a ValueError:
361
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000362 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000363 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000364 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000365 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000366
367If there's no blank space after a PS2 prompt ('...'), then `DocTest`
368will raise a ValueError:
369
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000370 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000371 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000372 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000373 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000374
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100375Compare `DocTest`:
376
377 >>> docstring = '''
378 ... >>> print 12
379 ... 12
380 ... '''
381 >>> test = parser.get_doctest(docstring, globs, 'some_test',
382 ... 'some_test', 20)
383 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
384 ... 'some_test', 20)
385 >>> test == same_test
386 True
387 >>> test != same_test
388 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100389 >>> hash(test) == hash(same_test)
390 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100391 >>> docstring = '''
392 ... >>> print 42
393 ... 42
394 ... '''
395 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
396 ... 'other_file', 10)
397 >>> test == other_test
398 False
399 >>> test != other_test
400 True
401
402Compare `DocTestCase`:
403
404 >>> DocTestCase = doctest.DocTestCase
405 >>> test_case = DocTestCase(test)
406 >>> same_test_case = DocTestCase(same_test)
407 >>> other_test_case = DocTestCase(other_test)
408 >>> test_case == same_test_case
409 True
410 >>> test_case != same_test_case
411 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100412 >>> hash(test_case) == hash(same_test_case)
413 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100414 >>> test == other_test_case
415 False
416 >>> test != other_test_case
417 True
418
Tim Peters8485b562004-08-04 18:46:34 +0000419"""
420
Zachary Ware7119b452013-11-24 02:21:57 -0600421class test_DocTestFinder:
422 def basics(): r"""
Tim Peters8485b562004-08-04 18:46:34 +0000423Unit tests for the `DocTestFinder` class.
424
425DocTestFinder is used to extract DocTests from an object's docstring
426and the docstrings of its contained objects. It can be used with
427modules, functions, classes, methods, staticmethods, classmethods, and
428properties.
429
430Finding Tests in Functions
431~~~~~~~~~~~~~~~~~~~~~~~~~~
432For a function whose docstring contains examples, DocTestFinder.find()
433will return a single test (for that function's docstring):
434
Tim Peters8485b562004-08-04 18:46:34 +0000435 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000436
437We'll simulate a __file__ attr that ends in pyc:
438
439 >>> import test.test_doctest
440 >>> old = test.test_doctest.__file__
441 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
442
Tim Peters8485b562004-08-04 18:46:34 +0000443 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000444
Guido van Rossum7131f842007-02-09 20:13:25 +0000445 >>> print(tests) # doctest: +ELLIPSIS
Hai Shi46605972020-08-04 00:49:18 +0800446 [<DocTest sample_func from ...:27 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000447
Tim Peters4de7c5c2004-08-23 22:38:05 +0000448The exact name depends on how test_doctest was invoked, so allow for
449leading path components.
450
451 >>> tests[0].filename # doctest: +ELLIPSIS
452 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000453
454 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000455
Jim Fulton07a349c2004-08-22 14:10:00 +0000456
Tim Peters8485b562004-08-04 18:46:34 +0000457 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000458 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000459 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000460
Edward Loper32ddbf72004-09-13 05:47:24 +0000461By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000462
463 >>> def no_docstring(v):
464 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000465 >>> finder.find(no_docstring)
466 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000467
468However, the optional argument `exclude_empty` to the DocTestFinder
469constructor can be used to exclude tests for objects with empty
470docstrings:
471
472 >>> def no_docstring(v):
473 ... pass
474 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
475 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000476 []
477
478If the function has a docstring with no examples, then a test with no
479examples is returned. (This lets `DocTestRunner` collect statistics
480about which functions have no tests -- but is that useful? And should
481an empty test also be created when there's no docstring?)
482
483 >>> def no_examples(v):
484 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000485 >>> finder.find(no_examples) # doctest: +ELLIPSIS
486 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000487
488Finding Tests in Classes
489~~~~~~~~~~~~~~~~~~~~~~~~
490For a class, DocTestFinder will create a test for the class's
491docstring, and will recursively explore its contents, including
492methods, classmethods, staticmethods, properties, and nested classes.
493
494 >>> finder = doctest.DocTestFinder()
495 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000496 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000497 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000498 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000499 3 SampleClass.NestedClass
500 1 SampleClass.NestedClass.__init__
501 1 SampleClass.__init__
502 2 SampleClass.a_classmethod
503 1 SampleClass.a_property
504 1 SampleClass.a_staticmethod
505 1 SampleClass.double
506 1 SampleClass.get
507
508New-style classes are also supported:
509
510 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000511 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000512 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000513 1 SampleNewStyleClass
514 1 SampleNewStyleClass.__init__
515 1 SampleNewStyleClass.double
516 1 SampleNewStyleClass.get
517
518Finding Tests in Modules
519~~~~~~~~~~~~~~~~~~~~~~~~
520For a module, DocTestFinder will create a test for the class's
521docstring, and will recursively explore its contents, including
522functions, classes, and the `__test__` dictionary, if it exists:
523
524 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000525 >>> import types
526 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000527 >>> def triple(val):
528 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000529 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000530 ... 33
531 ... '''
532 ... return val*3
533 >>> m.__dict__.update({
534 ... 'sample_func': sample_func,
535 ... 'SampleClass': SampleClass,
536 ... '__doc__': '''
537 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000538 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000539 ... module
540 ... ''',
541 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000542 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000543 ... 'c': triple}})
544
545 >>> finder = doctest.DocTestFinder()
546 >>> # Use module=test.test_doctest, to prevent doctest from
547 >>> # ignoring the objects since they weren't defined in m.
548 >>> import test.test_doctest
549 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000550 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000551 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000552 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000553 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000554 3 some_module.SampleClass.NestedClass
555 1 some_module.SampleClass.NestedClass.__init__
556 1 some_module.SampleClass.__init__
557 2 some_module.SampleClass.a_classmethod
558 1 some_module.SampleClass.a_property
559 1 some_module.SampleClass.a_staticmethod
560 1 some_module.SampleClass.double
561 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000562 1 some_module.__test__.c
563 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000564 1 some_module.sample_func
565
566Duplicate Removal
567~~~~~~~~~~~~~~~~~
568If a single object is listed twice (under different names), then tests
569will only be generated for it once:
570
Tim Petersf3f57472004-08-08 06:11:48 +0000571 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000572 >>> assert doctest_aliases.TwoNames.f
573 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000574 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000575 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000576 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000577 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000578 test.doctest_aliases.TwoNames
579
580 TwoNames.f and TwoNames.g are bound to the same object.
581 We can't guess which will be found in doctest's traversal of
582 TwoNames.__dict__ first, so we have to allow for either.
583
584 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000585 True
586
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000587Empty Tests
588~~~~~~~~~~~
589By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000590
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000591 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000592 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000593 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000594 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000595 3 SampleClass.NestedClass
596 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000597 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000598 2 SampleClass.a_classmethod
599 1 SampleClass.a_property
600 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000601 1 SampleClass.double
602 1 SampleClass.get
603
604By default, that excluded objects with no doctests. exclude_empty=False
605tells it to include (empty) tests for objects with no doctests. This feature
606is really to support backward compatibility in what doctest.master.summarize()
607displays.
608
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000609 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000610 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000611 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000612 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000613 3 SampleClass.NestedClass
614 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000615 0 SampleClass.NestedClass.get
616 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000617 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000618 2 SampleClass.a_classmethod
619 1 SampleClass.a_property
620 1 SampleClass.a_staticmethod
621 1 SampleClass.double
622 1 SampleClass.get
623
Tim Peters8485b562004-08-04 18:46:34 +0000624Turning off Recursion
625~~~~~~~~~~~~~~~~~~~~~
626DocTestFinder can be told not to look for tests in contained objects
627using the `recurse` flag:
628
629 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000630 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000631 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000632 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000633
634Line numbers
635~~~~~~~~~~~~
636DocTestFinder finds the line number of each example:
637
638 >>> def f(x):
639 ... '''
640 ... >>> x = 12
641 ...
642 ... some text
643 ...
644 ... >>> # examples are not created for comments & bare prompts.
645 ... >>>
646 ... ...
647 ...
648 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000649 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000650 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000651 ... >>> x//2
652 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000653 ... '''
654 >>> test = doctest.DocTestFinder().find(f)[0]
655 >>> [e.lineno for e in test.examples]
656 [1, 9, 12]
Zachary Ware7119b452013-11-24 02:21:57 -0600657"""
658
659 if int.__doc__: # simple check for --without-doc-strings, skip if lacking
660 def non_Python_modules(): r"""
Zachary Warea4b7a752013-11-24 01:19:09 -0600661
662Finding Doctests in Modules Not Written in Python
663~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
664DocTestFinder can also find doctests in most modules not written in Python.
665We'll use builtins as an example, since it almost certainly isn't written in
666plain ol' Python and is guaranteed to be available.
667
668 >>> import builtins
669 >>> tests = doctest.DocTestFinder().find(builtins)
sweeneydea81849b2020-04-22 17:05:48 -0400670 >>> 816 < len(tests) < 836 # approximate number of objects with docstrings
Zachary Ware7119b452013-11-24 02:21:57 -0600671 True
Zachary Warea4b7a752013-11-24 01:19:09 -0600672 >>> real_tests = [t for t in tests if len(t.examples) > 0]
Zachary Ware7119b452013-11-24 02:21:57 -0600673 >>> len(real_tests) # objects that actually have doctests
Niklas Fiekas8bd216d2020-05-29 18:28:02 +0200674 14
Zachary Warea4b7a752013-11-24 01:19:09 -0600675 >>> for t in real_tests:
676 ... print('{} {}'.format(len(t.examples), t.name))
677 ...
678 1 builtins.bin
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700679 5 builtins.bytearray.hex
680 5 builtins.bytes.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600681 3 builtins.float.as_integer_ratio
682 2 builtins.float.fromhex
683 2 builtins.float.hex
684 1 builtins.hex
685 1 builtins.int
Lisa Roach5ac70432018-09-13 23:56:23 -0700686 3 builtins.int.as_integer_ratio
Niklas Fiekas8bd216d2020-05-29 18:28:02 +0200687 2 builtins.int.bit_count
Zachary Warea4b7a752013-11-24 01:19:09 -0600688 2 builtins.int.bit_length
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700689 5 builtins.memoryview.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600690 1 builtins.oct
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -0700691 1 builtins.zip
Zachary Warea4b7a752013-11-24 01:19:09 -0600692
693Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
694'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
695and 'int' is a type.
Tim Peters8485b562004-08-04 18:46:34 +0000696"""
697
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500698
699class TestDocTestFinder(unittest.TestCase):
700
701 def test_empty_namespace_package(self):
702 pkg_name = 'doctest_empty_pkg'
Nick Coghland5d9e022018-03-25 23:03:10 +1000703 with tempfile.TemporaryDirectory() as parent_dir:
704 pkg_dir = os.path.join(parent_dir, pkg_name)
705 os.mkdir(pkg_dir)
706 sys.path.append(parent_dir)
707 try:
708 mod = importlib.import_module(pkg_name)
709 finally:
Hai Shi46605972020-08-04 00:49:18 +0800710 import_helper.forget(pkg_name)
Nick Coghland5d9e022018-03-25 23:03:10 +1000711 sys.path.pop()
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500712
Xtreak8289e272019-12-13 23:36:53 +0530713 include_empty_finder = doctest.DocTestFinder(exclude_empty=False)
714 exclude_empty_finder = doctest.DocTestFinder(exclude_empty=True)
715
716 self.assertEqual(len(include_empty_finder.find(mod)), 1)
717 self.assertEqual(len(exclude_empty_finder.find(mod)), 0)
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500718
Edward Loper00f8da72004-08-26 18:05:07 +0000719def test_DocTestParser(): r"""
720Unit tests for the `DocTestParser` class.
721
722DocTestParser is used to parse docstrings containing doctest examples.
723
724The `parse` method divides a docstring into examples and intervening
725text:
726
727 >>> s = '''
728 ... >>> x, y = 2, 3 # no output expected
729 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000730 ... ... print(x)
731 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000732 ... 2
733 ... 3
734 ...
735 ... Some text.
736 ... >>> x+y
737 ... 5
738 ... '''
739 >>> parser = doctest.DocTestParser()
740 >>> for piece in parser.parse(s):
741 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000742 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000743 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000744 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000745 Text: '\n'
746 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
747 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000748 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000749 Text: '\nSome text.\n'
750 Example: ('x+y\n', '5\n', 9)
751 Text: ''
752
753The `get_examples` method returns just the examples:
754
755 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000756 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000757 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000758 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000759 ('x+y\n', '5\n', 9)
760
761The `get_doctest` method creates a Test from the examples, along with the
762given arguments:
763
764 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
765 >>> (test.name, test.filename, test.lineno)
766 ('name', 'filename', 5)
767 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000768 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000769 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000770 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000771 ('x+y\n', '5\n', 9)
772"""
773
Tim Peters8485b562004-08-04 18:46:34 +0000774class test_DocTestRunner:
775 def basics(): r"""
776Unit tests for the `DocTestRunner` class.
777
778DocTestRunner is used to run DocTest test cases, and to accumulate
779statistics. Here's a simple DocTest case we can use:
780
781 >>> def f(x):
782 ... '''
783 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000784 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000785 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000786 ... >>> x//2
787 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000788 ... '''
789 >>> test = doctest.DocTestFinder().find(f)[0]
790
791The main DocTestRunner interface is the `run` method, which runs a
792given DocTest case in a given namespace (globs). It returns a tuple
793`(f,t)`, where `f` is the number of failed tests and `t` is the number
794of tried tests.
795
796 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000797 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000798
799If any example produces incorrect output, then the test runner reports
800the failure and proceeds to the next example:
801
802 >>> def f(x):
803 ... '''
804 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000805 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000806 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000807 ... >>> x//2
808 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000809 ... '''
810 >>> test = doctest.DocTestFinder().find(f)[0]
811 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000812 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000813 Trying:
814 x = 12
815 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000816 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000817 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000818 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000819 Expecting:
820 14
Tim Peters8485b562004-08-04 18:46:34 +0000821 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000822 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000823 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000824 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000825 Expected:
826 14
827 Got:
828 12
Edward Loperaacf0832004-08-26 01:19:50 +0000829 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000830 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000831 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000832 6
Tim Peters8485b562004-08-04 18:46:34 +0000833 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000834 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000835"""
836 def verbose_flag(): r"""
837The `verbose` flag makes the test runner generate more detailed
838output:
839
840 >>> def f(x):
841 ... '''
842 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000843 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000844 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845 ... >>> x//2
846 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000847 ... '''
848 >>> test = doctest.DocTestFinder().find(f)[0]
849
850 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000851 Trying:
852 x = 12
853 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000854 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000855 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000856 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000857 Expecting:
858 12
Tim Peters8485b562004-08-04 18:46:34 +0000859 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000860 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000861 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000862 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000863 6
Tim Peters8485b562004-08-04 18:46:34 +0000864 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000865 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000866
867If the `verbose` flag is unspecified, then the output will be verbose
868iff `-v` appears in sys.argv:
869
870 >>> # Save the real sys.argv list.
871 >>> old_argv = sys.argv
872
873 >>> # If -v does not appear in sys.argv, then output isn't verbose.
874 >>> sys.argv = ['test']
875 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000876 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000877
878 >>> # If -v does appear in sys.argv, then output is verbose.
879 >>> sys.argv = ['test', '-v']
880 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000881 Trying:
882 x = 12
883 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000884 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000885 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000886 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000887 Expecting:
888 12
Tim Peters8485b562004-08-04 18:46:34 +0000889 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000890 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000891 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000892 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000893 6
Tim Peters8485b562004-08-04 18:46:34 +0000894 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000895 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000896
897 >>> # Restore sys.argv
898 >>> sys.argv = old_argv
899
900In the remaining examples, the test runner's verbosity will be
901explicitly set, to ensure that the test behavior is consistent.
902 """
903 def exceptions(): r"""
904Tests of `DocTestRunner`'s exception handling.
905
906An expected exception is specified with a traceback message. The
907lines between the first line and the type/value may be omitted or
908replaced with any other string:
909
910 >>> def f(x):
911 ... '''
912 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000913 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000914 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000915 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000916 ... '''
917 >>> test = doctest.DocTestFinder().find(f)[0]
918 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000919 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000920
Edward Loper19b19582004-08-25 23:07:03 +0000921An example may not generate output before it raises an exception; if
922it does, then the traceback message will not be recognized as
923signaling an expected exception, so the example will be reported as an
924unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000925
926 >>> def f(x):
927 ... '''
928 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000929 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000930 ... pre-exception output
931 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000932 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000933 ... '''
934 >>> test = doctest.DocTestFinder().find(f)[0]
935 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000936 ... # doctest: +ELLIPSIS
937 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000938 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000939 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000940 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000941 Exception raised:
942 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000943 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000944 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000945
946Exception messages may contain newlines:
947
948 >>> def f(x):
949 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000950 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000951 ... Traceback (most recent call last):
952 ... ValueError: multi
953 ... line
954 ... message
955 ... '''
956 >>> test = doctest.DocTestFinder().find(f)[0]
957 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000958 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000959
960If an exception is expected, but an exception with the wrong type or
961message is raised, then it is reported as a failure:
962
963 >>> def f(x):
964 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000965 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000966 ... Traceback (most recent call last):
967 ... ValueError: wrong message
968 ... '''
969 >>> test = doctest.DocTestFinder().find(f)[0]
970 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000971 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000972 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000973 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000974 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000975 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000976 Expected:
977 Traceback (most recent call last):
978 ValueError: wrong message
979 Got:
980 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000981 ...
Tim Peters8485b562004-08-04 18:46:34 +0000982 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000983 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000984
Tim Peters1fbf9c52004-09-04 17:21:02 +0000985However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
986detail:
987
988 >>> def f(x):
989 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000990 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000991 ... Traceback (most recent call last):
992 ... ValueError: wrong message
993 ... '''
994 >>> test = doctest.DocTestFinder().find(f)[0]
995 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000996 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000997
Nick Coghlan5e76e942010-06-12 13:42:46 +0000998IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
999between Python versions. For example, in Python 2.x, the module path of
1000the exception is not in the output, but this will fail under Python 3:
1001
1002 >>> def f(x):
1003 ... r'''
1004 ... >>> from http.client import HTTPException
1005 ... >>> raise HTTPException('message')
1006 ... Traceback (most recent call last):
1007 ... HTTPException: message
1008 ... '''
1009 >>> test = doctest.DocTestFinder().find(f)[0]
1010 >>> doctest.DocTestRunner(verbose=False).run(test)
1011 ... # doctest: +ELLIPSIS
1012 **********************************************************************
1013 File ..., line 4, in f
1014 Failed example:
1015 raise HTTPException('message')
1016 Expected:
1017 Traceback (most recent call last):
1018 HTTPException: message
1019 Got:
1020 Traceback (most recent call last):
1021 ...
1022 http.client.HTTPException: message
1023 TestResults(failed=1, attempted=2)
1024
1025But in Python 3 the module path is included, and therefore a test must look
1026like the following test to succeed in Python 3. But that test will fail under
1027Python 2.
1028
1029 >>> def f(x):
1030 ... r'''
1031 ... >>> from http.client import HTTPException
1032 ... >>> raise HTTPException('message')
1033 ... Traceback (most recent call last):
1034 ... http.client.HTTPException: message
1035 ... '''
1036 >>> test = doctest.DocTestFinder().find(f)[0]
1037 >>> doctest.DocTestRunner(verbose=False).run(test)
1038 TestResults(failed=0, attempted=2)
1039
1040However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1041(or its unexpected absence) will be ignored:
1042
1043 >>> def f(x):
1044 ... r'''
1045 ... >>> from http.client import HTTPException
1046 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1047 ... Traceback (most recent call last):
1048 ... HTTPException: message
1049 ... '''
1050 >>> test = doctest.DocTestFinder().find(f)[0]
1051 >>> doctest.DocTestRunner(verbose=False).run(test)
1052 TestResults(failed=0, attempted=2)
1053
1054The module path will be completely ignored, so two different module paths will
1055still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1056be used when exceptions have changed module.
1057
1058 >>> def f(x):
1059 ... r'''
1060 ... >>> from http.client import HTTPException
1061 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1062 ... Traceback (most recent call last):
1063 ... foo.bar.HTTPException: message
1064 ... '''
1065 >>> test = doctest.DocTestFinder().find(f)[0]
1066 >>> doctest.DocTestRunner(verbose=False).run(test)
1067 TestResults(failed=0, attempted=2)
1068
Tim Peters1fbf9c52004-09-04 17:21:02 +00001069But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1070
1071 >>> def f(x):
1072 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001073 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001074 ... Traceback (most recent call last):
1075 ... TypeError: wrong type
1076 ... '''
1077 >>> test = doctest.DocTestFinder().find(f)[0]
1078 >>> doctest.DocTestRunner(verbose=False).run(test)
1079 ... # doctest: +ELLIPSIS
1080 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001081 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001082 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001083 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001084 Expected:
1085 Traceback (most recent call last):
1086 TypeError: wrong type
1087 Got:
1088 Traceback (most recent call last):
1089 ...
1090 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001091 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001092
Tim Petersf9a07f22013-12-03 21:02:05 -06001093If the exception does not have a message, you can still use
1094IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1095
1096 >>> def f(x):
1097 ... r'''
1098 ... >>> from http.client import HTTPException
1099 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1100 ... Traceback (most recent call last):
1101 ... foo.bar.HTTPException
1102 ... '''
1103 >>> test = doctest.DocTestFinder().find(f)[0]
1104 >>> doctest.DocTestRunner(verbose=False).run(test)
1105 TestResults(failed=0, attempted=2)
1106
1107Note that a trailing colon doesn't matter either:
1108
1109 >>> def f(x):
1110 ... r'''
1111 ... >>> from http.client import HTTPException
1112 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1113 ... Traceback (most recent call last):
1114 ... foo.bar.HTTPException:
1115 ... '''
1116 >>> test = doctest.DocTestFinder().find(f)[0]
1117 >>> doctest.DocTestRunner(verbose=False).run(test)
1118 TestResults(failed=0, attempted=2)
1119
Tim Peters8485b562004-08-04 18:46:34 +00001120If an exception is raised but not expected, then it is reported as an
1121unexpected exception:
1122
Tim Peters8485b562004-08-04 18:46:34 +00001123 >>> def f(x):
1124 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001125 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001126 ... 0
1127 ... '''
1128 >>> test = doctest.DocTestFinder().find(f)[0]
1129 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001130 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001131 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001132 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001133 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001134 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001135 Exception raised:
1136 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001137 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001138 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001139 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001140"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001141 def displayhook(): r"""
1142Test that changing sys.displayhook doesn't matter for doctest.
1143
1144 >>> import sys
1145 >>> orig_displayhook = sys.displayhook
1146 >>> def my_displayhook(x):
1147 ... print('hi!')
1148 >>> sys.displayhook = my_displayhook
1149 >>> def f():
1150 ... '''
1151 ... >>> 3
1152 ... 3
1153 ... '''
1154 >>> test = doctest.DocTestFinder().find(f)[0]
1155 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1156 >>> post_displayhook = sys.displayhook
1157
1158 We need to restore sys.displayhook now, so that we'll be able to test
1159 results.
1160
1161 >>> sys.displayhook = orig_displayhook
1162
1163 Ok, now we can check that everything is ok.
1164
1165 >>> r
1166 TestResults(failed=0, attempted=1)
1167 >>> post_displayhook is my_displayhook
1168 True
1169"""
Tim Peters8485b562004-08-04 18:46:34 +00001170 def optionflags(): r"""
1171Tests of `DocTestRunner`'s option flag handling.
1172
1173Several option flags can be used to customize the behavior of the test
1174runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001175to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001176together).
1177
1178The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1179and 1/0:
1180
1181 >>> def f(x):
1182 ... '>>> True\n1\n'
1183
1184 >>> # Without the flag:
1185 >>> test = doctest.DocTestFinder().find(f)[0]
1186 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001187 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001188
1189 >>> # With the flag:
1190 >>> test = doctest.DocTestFinder().find(f)[0]
1191 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1192 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001193 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001194 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001195 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001196 Failed example:
1197 True
1198 Expected:
1199 1
1200 Got:
1201 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001202 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001203
1204The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1205and the '<BLANKLINE>' marker:
1206
1207 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001208 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001209
1210 >>> # Without the flag:
1211 >>> test = doctest.DocTestFinder().find(f)[0]
1212 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001213 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001214
1215 >>> # With the flag:
1216 >>> test = doctest.DocTestFinder().find(f)[0]
1217 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1218 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001219 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001220 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001221 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001222 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001223 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001224 Expected:
1225 a
1226 <BLANKLINE>
1227 b
1228 Got:
1229 a
1230 <BLANKLINE>
1231 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001232 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001233
1234The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1235treated as equal:
1236
1237 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001238 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001239
1240 >>> # Without the flag:
1241 >>> test = doctest.DocTestFinder().find(f)[0]
1242 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001243 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001244 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001245 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001246 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001247 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001248 Expected:
1249 1 2
1250 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001251 Got:
1252 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001253 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001254
1255 >>> # With the flag:
1256 >>> test = doctest.DocTestFinder().find(f)[0]
1257 >>> flags = doctest.NORMALIZE_WHITESPACE
1258 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001259 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001260
Tim Peters026f8dc2004-08-19 16:38:58 +00001261 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001262 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001263 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1264 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1265
Tim Peters8485b562004-08-04 18:46:34 +00001266The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1267output to match any substring in the actual output:
1268
1269 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001270 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001271
1272 >>> # Without the flag:
1273 >>> test = doctest.DocTestFinder().find(f)[0]
1274 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001275 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001276 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001277 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001278 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001279 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001280 Expected:
1281 [0, 1, 2, ..., 14]
1282 Got:
1283 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001284 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001285
1286 >>> # With the flag:
1287 >>> test = doctest.DocTestFinder().find(f)[0]
1288 >>> flags = doctest.ELLIPSIS
1289 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001290 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001291
Tim Peterse594bee2004-08-22 01:47:51 +00001292 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001293
Guido van Rossume0192e52007-02-09 23:39:59 +00001294 >>> if 1:
1295 ... for i in range(100):
1296 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1297 ... print('!')
1298 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001299
Tim Peters026f8dc2004-08-19 16:38:58 +00001300 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001301
Guido van Rossume0192e52007-02-09 23:39:59 +00001302 >>> if 1: #doctest: +ELLIPSIS
1303 ... for i in range(20):
1304 ... print(i, end=' ')
1305 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001306 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001307
Tim Peters026f8dc2004-08-19 16:38:58 +00001308 Examples from the docs:
1309
Guido van Rossum805365e2007-05-07 22:24:25 +00001310 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001311 [0, 1, ..., 18, 19]
1312
Guido van Rossum805365e2007-05-07 22:24:25 +00001313 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001314 ... # doctest: +NORMALIZE_WHITESPACE
1315 [0, 1, ..., 18, 19]
1316
Thomas Wouters477c8d52006-05-27 19:21:47 +00001317The SKIP flag causes an example to be skipped entirely. I.e., the
1318example is not run. It can be useful in contexts where doctest
1319examples serve as both documentation and test cases, and an example
1320should be included for documentation purposes, but should not be
1321checked (e.g., because its output is random, or depends on resources
1322which would be unavailable.) The SKIP flag can also be used for
1323'commenting out' broken examples.
1324
1325 >>> import unavailable_resource # doctest: +SKIP
1326 >>> unavailable_resource.do_something() # doctest: +SKIP
1327 >>> unavailable_resource.blow_up() # doctest: +SKIP
1328 Traceback (most recent call last):
1329 ...
1330 UncheckedBlowUpError: Nobody checks me.
1331
1332 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001333 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001334 0.721216923889
1335
Edward Loper71f55af2004-08-26 01:41:51 +00001336The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001337and actual outputs to be displayed using a unified diff:
1338
1339 >>> def f(x):
1340 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001341 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001342 ... a
1343 ... B
1344 ... c
1345 ... d
1346 ... f
1347 ... g
1348 ... h
1349 ... '''
1350
1351 >>> # Without the flag:
1352 >>> test = doctest.DocTestFinder().find(f)[0]
1353 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001354 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001355 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001356 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001357 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001358 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001359 Expected:
1360 a
1361 B
1362 c
1363 d
1364 f
1365 g
1366 h
1367 Got:
1368 a
1369 b
1370 c
1371 d
1372 e
1373 f
1374 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001375 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001376
1377 >>> # With the flag:
1378 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001379 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001380 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001381 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001382 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001383 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001384 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001385 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001386 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001387 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001388 a
1389 -B
1390 +b
1391 c
1392 d
1393 +e
1394 f
1395 g
1396 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001397 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001398
Edward Loper71f55af2004-08-26 01:41:51 +00001399The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001400and actual outputs to be displayed using a context diff:
1401
Edward Loper71f55af2004-08-26 01:41:51 +00001402 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001403 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001404 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001405 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001406 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001407 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001408 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001409 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001410 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001411 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001412 ***************
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 f
1419 g
1420 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001421 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001422 a
1423 ! b
1424 c
1425 d
1426 + e
1427 f
1428 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001429 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001430
1431
Edward Loper71f55af2004-08-26 01:41:51 +00001432The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001433used by the popular ndiff.py utility. This does intraline difference
1434marking, as well as interline differences.
1435
1436 >>> def f(x):
1437 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001438 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001439 ... a b c d e f g h i j k 1 m
1440 ... '''
1441 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001442 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001443 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001444 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001445 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001446 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001447 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001448 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001449 Differences (ndiff with -expected +actual):
1450 - a b c d e f g h i j k 1 m
1451 ? ^
1452 + a b c d e f g h i j k l m
1453 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001454 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001455
Ezio Melotti13925002011-03-16 11:05:33 +02001456The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001457failing example:
1458
1459 >>> def f(x):
1460 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001461 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001462 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001463 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001464 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001465 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001466 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001467 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001468 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001469 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001470 ... 500
1471 ... '''
1472 >>> test = doctest.DocTestFinder().find(f)[0]
1473 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1474 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001475 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001476 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001477 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001478 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001479 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001480 Expected:
1481 200
1482 Got:
1483 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001484 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001485
Ezio Melotti13925002011-03-16 11:05:33 +02001486However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001487
1488 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001489 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001490 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001491 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001492 Expecting:
1493 1
1494 ok
1495 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001496 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001497 Expecting:
1498 200
1499 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001500 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001501 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001502 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001503 Expected:
1504 200
1505 Got:
1506 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001507 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001508
R David Murray5a9d7062012-11-21 15:09:21 -05001509The FAIL_FAST flag causes the runner to exit after the first failing example,
1510so subsequent examples are not even attempted:
1511
1512 >>> flags = doctest.FAIL_FAST
1513 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1514 ... # doctest: +ELLIPSIS
1515 **********************************************************************
1516 File ..., line 5, in f
1517 Failed example:
1518 print(2) # first failure
1519 Expected:
1520 200
1521 Got:
1522 2
1523 TestResults(failed=1, attempted=2)
1524
1525Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1526FAIL_FAST only:
1527
1528 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1529 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1530 ... # doctest: +ELLIPSIS
1531 **********************************************************************
1532 File ..., line 5, in f
1533 Failed example:
1534 print(2) # first failure
1535 Expected:
1536 200
1537 Got:
1538 2
1539 TestResults(failed=1, attempted=2)
1540
1541For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1542exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001543
1544 >>> def f(x):
1545 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001546 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001547 ... 1
1548 ... >>> raise ValueError(2) # first failure
1549 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001550 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001551 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001552 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001553 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001554 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001555 ... 500
1556 ... '''
1557 >>> test = doctest.DocTestFinder().find(f)[0]
1558 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1559 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1560 ... # doctest: +ELLIPSIS
1561 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001562 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001563 Failed example:
1564 raise ValueError(2) # first failure
1565 Exception raised:
1566 ...
1567 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001568 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001569 >>> flags = doctest.FAIL_FAST
1570 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1571 ... # doctest: +ELLIPSIS
1572 **********************************************************************
1573 File ..., line 5, in f
1574 Failed example:
1575 raise ValueError(2) # first failure
1576 Exception raised:
1577 ...
1578 ValueError: 2
1579 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001580
Thomas Wouters477c8d52006-05-27 19:21:47 +00001581New option flags can also be registered, via register_optionflag(). Here
1582we reach into doctest's internals a bit.
1583
1584 >>> unlikely = "UNLIKELY_OPTION_NAME"
1585 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1586 False
1587 >>> new_flag_value = doctest.register_optionflag(unlikely)
1588 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1589 True
1590
1591Before 2.4.4/2.5, registering a name more than once erroneously created
1592more than one flag value. Here we verify that's fixed:
1593
1594 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1595 >>> redundant_flag_value == new_flag_value
1596 True
1597
1598Clean up.
1599 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1600
Tim Petersc6cbab02004-08-22 19:43:28 +00001601 """
1602
Tim Peters8485b562004-08-04 18:46:34 +00001603 def option_directives(): r"""
1604Tests of `DocTestRunner`'s option directive mechanism.
1605
Edward Loper74bca7a2004-08-12 02:27:44 +00001606Option directives can be used to turn option flags on or off for a
1607single example. To turn an option on for an example, follow that
1608example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001609
1610 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001611 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001612 ... [0, 1, ..., 9]
1613 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001614 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001615 ... [0, 1, ..., 9]
1616 ... '''
1617 >>> test = doctest.DocTestFinder().find(f)[0]
1618 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001619 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001620 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001621 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001622 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001623 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001624 Expected:
1625 [0, 1, ..., 9]
1626 Got:
1627 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001628 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001629
1630To turn an option off for an example, follow that example with a
1631comment of the form ``# doctest: -OPTION``:
1632
1633 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001634 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001635 ... [0, 1, ..., 9]
1636 ...
1637 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001638 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001639 ... [0, 1, ..., 9]
1640 ... '''
1641 >>> test = doctest.DocTestFinder().find(f)[0]
1642 >>> doctest.DocTestRunner(verbose=False,
1643 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001644 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001645 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001646 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001647 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001648 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001649 Expected:
1650 [0, 1, ..., 9]
1651 Got:
1652 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001653 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001654
1655Option directives affect only the example that they appear with; they
1656do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001657
Edward Loper74bca7a2004-08-12 02:27:44 +00001658 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001659 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001660 ... [0, 1, ..., 9]
1661 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001662 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001663 ... [0, 1, ..., 9]
1664 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001665 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001666 ... [0, 1, ..., 9]
1667 ... '''
1668 >>> test = doctest.DocTestFinder().find(f)[0]
1669 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001670 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001671 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001672 File ..., line 2, 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]
Tim Peters8485b562004-08-04 18:46:34 +00001679 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001680 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001681 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001682 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001683 Expected:
1684 [0, 1, ..., 9]
1685 Got:
1686 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001687 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001688
Edward Loper74bca7a2004-08-12 02:27:44 +00001689Multiple options may be modified by a single option directive. They
1690may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001691
1692 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001693 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001694 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001695 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001696 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001697 ... [0, 1, ..., 9]
1698 ... '''
1699 >>> test = doctest.DocTestFinder().find(f)[0]
1700 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001701 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001702 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001703 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001704 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001705 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001706 Expected:
1707 [0, 1, ..., 9]
1708 Got:
1709 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001710 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001711
1712 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001713 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001714 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001715 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001716 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1717 ... [0, 1, ..., 9]
1718 ... '''
1719 >>> test = doctest.DocTestFinder().find(f)[0]
1720 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001721 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001722 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001723 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001724 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001725 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001726 Expected:
1727 [0, 1, ..., 9]
1728 Got:
1729 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001730 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001731
1732 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001733 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001734 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001735 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001736 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1737 ... [0, 1, ..., 9]
1738 ... '''
1739 >>> test = doctest.DocTestFinder().find(f)[0]
1740 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001741 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001742 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001743 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001744 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001745 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001746 Expected:
1747 [0, 1, ..., 9]
1748 Got:
1749 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001750 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001751
1752The option directive may be put on the line following the source, as
1753long as a continuation prompt is used:
1754
1755 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001756 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001757 ... ... # doctest: +ELLIPSIS
1758 ... [0, 1, ..., 9]
1759 ... '''
1760 >>> test = doctest.DocTestFinder().find(f)[0]
1761 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001762 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001763
Edward Loper74bca7a2004-08-12 02:27:44 +00001764For examples with multi-line source, the option directive may appear
1765at the end of any line:
1766
1767 >>> def f(x): r'''
1768 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001769 ... ... print(' ', x, end='', sep='')
1770 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001771 ...
1772 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001773 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1774 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001775 ... '''
1776 >>> test = doctest.DocTestFinder().find(f)[0]
1777 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001778 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001779
1780If more than one line of an example with multi-line source has an
1781option directive, then they are combined:
1782
1783 >>> def f(x): r'''
1784 ... Should fail (option directive not on the last line):
1785 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001786 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001787 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001788 ... '''
1789 >>> test = doctest.DocTestFinder().find(f)[0]
1790 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001791 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001792
1793It is an error to have a comment of the form ``# doctest:`` that is
1794*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1795``OPTION`` is an option that has been registered with
1796`register_option`:
1797
1798 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001799 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001800 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1801 Traceback (most recent call last):
1802 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1803
1804 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001805 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001806 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1807 Traceback (most recent call last):
1808 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1809
1810It is an error to use an option directive on a line that contains no
1811source:
1812
1813 >>> s = '>>> # doctest: +ELLIPSIS'
1814 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1815 Traceback (most recent call last):
1816 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 +00001817"""
1818
1819def test_testsource(): r"""
1820Unit tests for `testsource()`.
1821
1822The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001823test with that name in that module, and converts it to a script. The
1824example code is converted to regular Python code. The surrounding
1825words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001826
1827 >>> import test.test_doctest
1828 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001829 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001830 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001831 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001832 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001833 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001834 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001835 #
Edward Lopera5db6002004-08-12 02:41:30 +00001836 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001837 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001838
1839 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001840 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001841 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001842 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001843 ## 1
1844 ## 2
1845 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001846 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001847
1848 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001849 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001850 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001851 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001852 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001853 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001854 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001855 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001856 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001857"""
1858
1859def test_debug(): r"""
1860
1861Create a docstring that we want to debug:
1862
1863 >>> s = '''
1864 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001865 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001866 ... 12
1867 ... '''
1868
1869Create some fake stdin input, to feed to the debugger:
1870
Tim Peters8485b562004-08-04 18:46:34 +00001871 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001872 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001873
1874Run the debugger on the docstring, and then restore sys.stdin.
1875
Edward Loper2de91ba2004-08-27 02:07:46 +00001876 >>> try: doctest.debug_src(s)
1877 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001879 (Pdb) next
1880 12
Tim Peters8485b562004-08-04 18:46:34 +00001881 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001882 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001883 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001884 12
1885 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001886
1887"""
1888
Brett Cannon31f59292011-02-21 19:29:56 +00001889if not hasattr(sys, 'gettrace') or not sys.gettrace():
1890 def test_pdb_set_trace():
1891 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001892
Brett Cannon31f59292011-02-21 19:29:56 +00001893 You can use pdb.set_trace from a doctest. To do so, you must
1894 retrieve the set_trace function from the pdb module at the time
1895 you use it. The doctest module changes sys.stdout so that it can
1896 capture program output. It also temporarily replaces pdb.set_trace
1897 with a version that restores stdout. This is necessary for you to
1898 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001899
Brett Cannon31f59292011-02-21 19:29:56 +00001900 >>> doc = '''
1901 ... >>> x = 42
1902 ... >>> raise Exception('clé')
1903 ... Traceback (most recent call last):
1904 ... Exception: clé
1905 ... >>> import pdb; pdb.set_trace()
1906 ... '''
1907 >>> parser = doctest.DocTestParser()
1908 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1909 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001910
Brett Cannon31f59292011-02-21 19:29:56 +00001911 To demonstrate this, we'll create a fake standard input that
1912 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001913
Brett Cannon31f59292011-02-21 19:29:56 +00001914 >>> real_stdin = sys.stdin
1915 >>> sys.stdin = _FakeInput([
1916 ... 'print(x)', # print data defined by the example
1917 ... 'continue', # stop debugging
1918 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001919
Brett Cannon31f59292011-02-21 19:29:56 +00001920 >>> try: runner.run(test)
1921 ... finally: sys.stdin = real_stdin
1922 --Return--
1923 > <doctest foo-bar@baz[2]>(1)<module>()->None
1924 -> import pdb; pdb.set_trace()
1925 (Pdb) print(x)
1926 42
1927 (Pdb) continue
1928 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001929
Brett Cannon31f59292011-02-21 19:29:56 +00001930 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001931
Brett Cannon31f59292011-02-21 19:29:56 +00001932 >>> def calls_set_trace():
1933 ... y=2
1934 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001935
Brett Cannon31f59292011-02-21 19:29:56 +00001936 >>> doc = '''
1937 ... >>> x=1
1938 ... >>> calls_set_trace()
1939 ... '''
1940 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1941 >>> real_stdin = sys.stdin
1942 >>> sys.stdin = _FakeInput([
1943 ... 'print(y)', # print data defined in the function
1944 ... 'up', # out of function
1945 ... 'print(x)', # print data defined by the example
1946 ... 'continue', # stop debugging
1947 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001948
Brett Cannon31f59292011-02-21 19:29:56 +00001949 >>> try:
1950 ... runner.run(test)
1951 ... finally:
1952 ... sys.stdin = real_stdin
1953 --Return--
Serhiy Storchakae437a102016-04-24 21:41:02 +03001954 > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
Brett Cannon31f59292011-02-21 19:29:56 +00001955 -> import pdb; pdb.set_trace()
1956 (Pdb) print(y)
1957 2
1958 (Pdb) up
1959 > <doctest foo-bar@baz[1]>(1)<module>()
1960 -> calls_set_trace()
1961 (Pdb) print(x)
1962 1
1963 (Pdb) continue
1964 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001965
Brett Cannon31f59292011-02-21 19:29:56 +00001966 During interactive debugging, source code is shown, even for
1967 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001968
Brett Cannon31f59292011-02-21 19:29:56 +00001969 >>> doc = '''
1970 ... >>> def f(x):
1971 ... ... g(x*2)
1972 ... >>> def g(x):
1973 ... ... print(x+3)
1974 ... ... import pdb; pdb.set_trace()
1975 ... >>> f(3)
1976 ... '''
1977 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1978 >>> real_stdin = sys.stdin
1979 >>> sys.stdin = _FakeInput([
1980 ... 'list', # list source from example 2
1981 ... 'next', # return from g()
1982 ... 'list', # list source from example 1
1983 ... 'next', # return from f()
1984 ... 'list', # list source from example 3
1985 ... 'continue', # stop debugging
1986 ... ''])
1987 >>> try: runner.run(test)
1988 ... finally: sys.stdin = real_stdin
1989 ... # doctest: +NORMALIZE_WHITESPACE
1990 --Return--
1991 > <doctest foo-bar@baz[1]>(3)g()->None
1992 -> import pdb; pdb.set_trace()
1993 (Pdb) list
1994 1 def g(x):
1995 2 print(x+3)
1996 3 -> import pdb; pdb.set_trace()
1997 [EOF]
1998 (Pdb) next
1999 --Return--
2000 > <doctest foo-bar@baz[0]>(2)f()->None
2001 -> g(x*2)
2002 (Pdb) list
2003 1 def f(x):
2004 2 -> g(x*2)
2005 [EOF]
2006 (Pdb) next
2007 --Return--
2008 > <doctest foo-bar@baz[2]>(1)<module>()->None
2009 -> f(3)
2010 (Pdb) list
2011 1 -> f(3)
2012 [EOF]
2013 (Pdb) continue
2014 **********************************************************************
2015 File "foo-bar@baz.py", line 7, in foo-bar@baz
2016 Failed example:
2017 f(3)
2018 Expected nothing
2019 Got:
2020 9
2021 TestResults(failed=1, attempted=3)
2022 """
Jim Fulton356fd192004-08-09 11:34:47 +00002023
Brett Cannon31f59292011-02-21 19:29:56 +00002024 def test_pdb_set_trace_nested():
2025 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00002026
Brett Cannon31f59292011-02-21 19:29:56 +00002027 >>> class C(object):
2028 ... def calls_set_trace(self):
2029 ... y = 1
2030 ... import pdb; pdb.set_trace()
2031 ... self.f1()
2032 ... y = 2
2033 ... def f1(self):
2034 ... x = 1
2035 ... self.f2()
2036 ... x = 2
2037 ... def f2(self):
2038 ... z = 1
2039 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002040
Brett Cannon31f59292011-02-21 19:29:56 +00002041 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002042
Brett Cannon31f59292011-02-21 19:29:56 +00002043 >>> doc = '''
2044 ... >>> a = 1
2045 ... >>> calls_set_trace()
2046 ... '''
2047 >>> parser = doctest.DocTestParser()
2048 >>> runner = doctest.DocTestRunner(verbose=False)
2049 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2050 >>> real_stdin = sys.stdin
2051 >>> sys.stdin = _FakeInput([
2052 ... 'print(y)', # print data defined in the function
2053 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2054 ... 'up', 'print(x)',
2055 ... 'up', 'print(y)',
2056 ... 'up', 'print(foo)',
2057 ... 'continue', # stop debugging
2058 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002059
Brett Cannon31f59292011-02-21 19:29:56 +00002060 >>> try:
2061 ... runner.run(test)
2062 ... finally:
2063 ... sys.stdin = real_stdin
2064 ... # doctest: +REPORT_NDIFF
2065 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2066 -> self.f1()
2067 (Pdb) print(y)
2068 1
2069 (Pdb) step
2070 --Call--
2071 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2072 -> def f1(self):
2073 (Pdb) step
2074 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2075 -> x = 1
2076 (Pdb) step
2077 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2078 -> self.f2()
2079 (Pdb) step
2080 --Call--
2081 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2082 -> def f2(self):
2083 (Pdb) step
2084 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2085 -> z = 1
2086 (Pdb) step
2087 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2088 -> z = 2
2089 (Pdb) print(z)
2090 1
2091 (Pdb) up
2092 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2093 -> self.f2()
2094 (Pdb) print(x)
2095 1
2096 (Pdb) up
2097 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2098 -> self.f1()
2099 (Pdb) print(y)
2100 1
2101 (Pdb) up
2102 > <doctest foo-bar@baz[1]>(1)<module>()
2103 -> calls_set_trace()
2104 (Pdb) print(foo)
2105 *** NameError: name 'foo' is not defined
2106 (Pdb) continue
2107 TestResults(failed=0, attempted=2)
2108 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002109
Tim Peters19397e52004-08-06 22:02:59 +00002110def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002111 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002112
2113 We create a Suite by providing a module. A module can be provided
2114 by passing a module object:
2115
2116 >>> import unittest
2117 >>> import test.sample_doctest
2118 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2119 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002120 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002121
2122 We can also supply the module by name:
2123
2124 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2125 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002126 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002127
R David Murray5abd76a2012-09-10 10:15:58 -04002128 The module need not contain any doctest examples:
2129
2130 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2131 >>> suite.run(unittest.TestResult())
2132 <unittest.result.TestResult run=0 errors=0 failures=0>
2133
R David Murray1976d9b2014-04-14 20:28:36 -04002134 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002135
R David Murray1976d9b2014-04-14 20:28:36 -04002136 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002137 >>> suite.run(unittest.TestResult())
2138 <unittest.result.TestResult run=0 errors=0 failures=0>
2139
Tim Peters19397e52004-08-06 22:02:59 +00002140 We can use the current module:
2141
2142 >>> suite = test.sample_doctest.test_suite()
2143 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002144 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002145
R David Murray1976d9b2014-04-14 20:28:36 -04002146 We can also provide a DocTestFinder:
2147
2148 >>> finder = doctest.DocTestFinder()
2149 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2150 ... test_finder=finder)
2151 >>> suite.run(unittest.TestResult())
2152 <unittest.result.TestResult run=9 errors=0 failures=4>
2153
2154 The DocTestFinder need not return any tests:
2155
2156 >>> finder = doctest.DocTestFinder()
2157 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2158 ... test_finder=finder)
2159 >>> suite.run(unittest.TestResult())
2160 <unittest.result.TestResult run=0 errors=0 failures=0>
2161
Tim Peters19397e52004-08-06 22:02:59 +00002162 We can supply global variables. If we pass globs, they will be
2163 used instead of the module globals. Here we'll pass an empty
2164 globals, triggering an extra error:
2165
2166 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2167 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002168 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002169
2170 Alternatively, we can provide extra globals. Here we'll make an
2171 error go away by providing an extra global variable:
2172
2173 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2174 ... extraglobs={'y': 1})
2175 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002176 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002177
2178 You can pass option flags. Here we'll cause an extra error
2179 by disabling the blank-line feature:
2180
2181 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002182 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002183 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002184 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002185
Tim Peters1e277ee2004-08-07 05:37:52 +00002186 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002187
Jim Fultonf54bad42004-08-28 14:57:56 +00002188 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002189 ... import test.test_doctest
2190 ... test.test_doctest.sillySetup = True
2191
Jim Fultonf54bad42004-08-28 14:57:56 +00002192 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002193 ... import test.test_doctest
2194 ... del test.test_doctest.sillySetup
2195
2196 Here, we installed a silly variable that the test expects:
2197
2198 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2199 ... setUp=setUp, tearDown=tearDown)
2200 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002201 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002202
2203 But the tearDown restores sanity:
2204
2205 >>> import test.test_doctest
2206 >>> test.test_doctest.sillySetup
2207 Traceback (most recent call last):
2208 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002209 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002210
Berker Peksag4882cac2015-04-14 09:30:01 +03002211 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002212 we'll use the setUp function to supply the missing variable y:
2213
2214 >>> def setUp(test):
2215 ... test.globs['y'] = 1
2216
2217 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2218 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002219 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002220
2221 Here, we didn't need to use a tearDown function because we
2222 modified the test globals, which are a copy of the
2223 sample_doctest module dictionary. The test globals are
2224 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002225 """
2226
2227def test_DocFileSuite():
2228 """We can test tests found in text files using a DocFileSuite.
2229
2230 We create a suite by providing the names of one or more text
2231 files that include examples:
2232
2233 >>> import unittest
2234 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002235 ... 'test_doctest2.txt',
2236 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002237 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002238 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002239
2240 The test files are looked for in the directory containing the
2241 calling module. A package keyword argument can be provided to
2242 specify a different relative location.
2243
2244 >>> import unittest
2245 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2246 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002247 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002248 ... package='test')
2249 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002250 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002251
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002252 Support for using a package's __loader__.get_data() is also
2253 provided.
2254
2255 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002256 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002257 >>> if not hasattr(test, '__loader__'):
2258 ... test.__loader__ = pkgutil.get_loader(test)
2259 ... added_loader = True
2260 >>> try:
2261 ... suite = doctest.DocFileSuite('test_doctest.txt',
2262 ... 'test_doctest2.txt',
2263 ... 'test_doctest4.txt',
2264 ... package='test')
2265 ... suite.run(unittest.TestResult())
2266 ... finally:
2267 ... if added_loader:
2268 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002269 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002270
Edward Loper0273f5b2004-09-18 20:27:04 +00002271 '/' should be used as a path separator. It will be converted
2272 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002273
2274 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2275 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002276 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002277
Edward Loper0273f5b2004-09-18 20:27:04 +00002278 If DocFileSuite is used from an interactive session, then files
2279 are resolved relative to the directory of sys.argv[0]:
2280
Christian Heimes45f9af32007-11-27 21:50:00 +00002281 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002282 >>> save_argv = sys.argv
2283 >>> sys.argv = [test.test_doctest.__file__]
2284 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002285 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002286 >>> sys.argv = save_argv
2287
Edward Loper052d0cd2004-09-19 17:19:33 +00002288 By setting `module_relative=False`, os-specific paths may be
2289 used (including absolute paths and paths relative to the
2290 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002291
2292 >>> # Get the absolute path of the test package.
2293 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2294 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2295
2296 >>> # Use it to find the absolute path of test_doctest.txt.
2297 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2298
Edward Loper052d0cd2004-09-19 17:19:33 +00002299 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002300 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002301 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002302
Edward Loper052d0cd2004-09-19 17:19:33 +00002303 It is an error to specify `package` when `module_relative=False`:
2304
2305 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2306 ... package='test')
2307 Traceback (most recent call last):
2308 ValueError: Package may only be specified for module-relative paths.
2309
Tim Peters19397e52004-08-06 22:02:59 +00002310 You can specify initial global variables:
2311
2312 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2313 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002314 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002315 ... globs={'favorite_color': 'blue'})
2316 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002317 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002318
2319 In this case, we supplied a missing favorite color. You can
2320 provide doctest options:
2321
2322 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2323 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002324 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002325 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2326 ... globs={'favorite_color': 'blue'})
2327 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002328 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002329
2330 And, you can provide setUp and tearDown functions:
2331
Jim Fultonf54bad42004-08-28 14:57:56 +00002332 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002333 ... import test.test_doctest
2334 ... test.test_doctest.sillySetup = True
2335
Jim Fultonf54bad42004-08-28 14:57:56 +00002336 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002337 ... import test.test_doctest
2338 ... del test.test_doctest.sillySetup
2339
2340 Here, we installed a silly variable that the test expects:
2341
2342 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2343 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002344 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002345 ... setUp=setUp, tearDown=tearDown)
2346 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002347 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002348
2349 But the tearDown restores sanity:
2350
2351 >>> import test.test_doctest
2352 >>> test.test_doctest.sillySetup
2353 Traceback (most recent call last):
2354 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002355 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002356
Berker Peksag4882cac2015-04-14 09:30:01 +03002357 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002358 Here, we'll use a setUp function to set the favorite color in
2359 test_doctest.txt:
2360
2361 >>> def setUp(test):
2362 ... test.globs['favorite_color'] = 'blue'
2363
2364 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2365 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002366 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002367
2368 Here, we didn't need to use a tearDown function because we
2369 modified the test globals. The test globals are
2370 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002371
Fred Drake7c404a42004-12-21 23:46:34 +00002372 Tests in a file run using `DocFileSuite` can also access the
2373 `__file__` global, which is set to the name of the file
2374 containing the tests:
2375
Benjamin Petersonab078e92016-07-13 21:13:29 -07002376 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
Fred Drake7c404a42004-12-21 23:46:34 +00002377 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002378 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002379
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002380 If the tests contain non-ASCII characters, we have to specify which
2381 encoding the file is encoded with. We do so by using the `encoding`
2382 parameter:
2383
2384 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2385 ... 'test_doctest2.txt',
2386 ... 'test_doctest4.txt',
2387 ... encoding='utf-8')
2388 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002389 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002390
Jim Fultonf54bad42004-08-28 14:57:56 +00002391 """
Tim Peters19397e52004-08-06 22:02:59 +00002392
Jim Fulton07a349c2004-08-22 14:10:00 +00002393def test_trailing_space_in_test():
2394 """
Tim Petersa7def722004-08-23 22:13:22 +00002395 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002396
Jim Fulton07a349c2004-08-22 14:10:00 +00002397 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002398 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002399 foo \n
2400 """
Tim Peters19397e52004-08-06 22:02:59 +00002401
Yury Selivanovb532df62014-12-08 15:00:05 -05002402class Wrapper:
2403 def __init__(self, func):
2404 self.func = func
2405 functools.update_wrapper(self, func)
2406
2407 def __call__(self, *args, **kwargs):
2408 self.func(*args, **kwargs)
2409
2410@Wrapper
2411def test_look_in_unwrapped():
2412 """
2413 Docstrings in wrapped functions must be detected as well.
2414
2415 >>> 'one other test'
2416 'one other test'
2417 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002418
2419def test_unittest_reportflags():
2420 """Default unittest reporting flags can be set to control reporting
2421
2422 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2423 only the first failure of each test. First, we'll look at the
2424 output without the flag. The file test_doctest.txt file has two
2425 tests. They both fail if blank lines are disabled:
2426
2427 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2428 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2429 >>> import unittest
2430 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002431 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002432 Traceback ...
2433 Failed example:
2434 favorite_color
2435 ...
2436 Failed example:
2437 if 1:
2438 ...
2439
2440 Note that we see both failures displayed.
2441
2442 >>> old = doctest.set_unittest_reportflags(
2443 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2444
2445 Now, when we run the test:
2446
2447 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002448 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002449 Traceback ...
2450 Failed example:
2451 favorite_color
2452 Exception raised:
2453 ...
2454 NameError: name 'favorite_color' is not defined
2455 <BLANKLINE>
2456 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002457
Jim Fultonf54bad42004-08-28 14:57:56 +00002458 We get only the first failure.
2459
2460 If we give any reporting options when we set up the tests,
2461 however:
2462
2463 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2464 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2465
2466 Then the default eporting options are ignored:
2467
2468 >>> result = suite.run(unittest.TestResult())
Pablo Galindoc5dc60e2019-01-10 14:29:40 +00002469
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302470 *NOTE*: These doctest are intentionally not placed in raw string to depict
2471 the trailing whitespace using `\x20` in the diff below.
2472
Guido van Rossum7131f842007-02-09 20:13:25 +00002473 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002474 Traceback ...
2475 Failed example:
2476 favorite_color
2477 ...
2478 Failed example:
2479 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002480 print('a')
2481 print()
2482 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002483 Differences (ndiff with -expected +actual):
2484 a
2485 - <BLANKLINE>
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302486 +\x20
Jim Fultonf54bad42004-08-28 14:57:56 +00002487 b
2488 <BLANKLINE>
2489 <BLANKLINE>
2490
2491
2492 Test runners can restore the formatting flags after they run:
2493
2494 >>> ignored = doctest.set_unittest_reportflags(old)
2495
2496 """
2497
Edward Loper052d0cd2004-09-19 17:19:33 +00002498def test_testfile(): r"""
2499Tests for the `testfile()` function. This function runs all the
Min ho Kimc4cacc82019-07-31 08:16:13 +10002500doctest examples in a given file. In its simple invocation, it is
Edward Loper052d0cd2004-09-19 17:19:33 +00002501called with the name of a file, which is taken to be relative to the
2502calling module. The return value is (#failures, #tests).
2503
Florent Xicluna59250852010-02-27 14:21:57 +00002504We don't want `-v` in sys.argv for these tests.
2505
2506 >>> save_argv = sys.argv
2507 >>> if '-v' in sys.argv:
2508 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2509
2510
Edward Loper052d0cd2004-09-19 17:19:33 +00002511 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2512 **********************************************************************
2513 File "...", line 6, in test_doctest.txt
2514 Failed example:
2515 favorite_color
2516 Exception raised:
2517 ...
2518 NameError: name 'favorite_color' is not defined
2519 **********************************************************************
2520 1 items had failures:
2521 1 of 2 in test_doctest.txt
2522 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002523 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002524 >>> doctest.master = None # Reset master.
2525
2526(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002527`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002528same name.)
2529
2530Globals may be specified with the `globs` and `extraglobs` parameters:
2531
2532 >>> globs = {'favorite_color': 'blue'}
2533 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002534 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002535 >>> doctest.master = None # Reset master.
2536
2537 >>> extraglobs = {'favorite_color': 'red'}
2538 >>> doctest.testfile('test_doctest.txt', globs=globs,
2539 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2540 **********************************************************************
2541 File "...", line 6, in test_doctest.txt
2542 Failed example:
2543 favorite_color
2544 Expected:
2545 'blue'
2546 Got:
2547 'red'
2548 **********************************************************************
2549 1 items had failures:
2550 1 of 2 in test_doctest.txt
2551 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002552 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002553 >>> doctest.master = None # Reset master.
2554
2555The file may be made relative to a given module or package, using the
2556optional `module_relative` parameter:
2557
2558 >>> doctest.testfile('test_doctest.txt', globs=globs,
2559 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002560 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002561 >>> doctest.master = None # Reset master.
2562
Ezio Melotti13925002011-03-16 11:05:33 +02002563Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002564
2565 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2566 Trying:
2567 favorite_color
2568 Expecting:
2569 'blue'
2570 ok
2571 Trying:
2572 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002573 print('a')
2574 print()
2575 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002576 Expecting:
2577 a
2578 <BLANKLINE>
2579 b
2580 ok
2581 1 items passed all tests:
2582 2 tests in test_doctest.txt
2583 2 tests in 1 items.
2584 2 passed and 0 failed.
2585 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002586 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002587 >>> doctest.master = None # Reset master.
2588
2589The name of the test may be specified with the optional `name`
2590parameter:
2591
2592 >>> doctest.testfile('test_doctest.txt', name='newname')
2593 ... # doctest: +ELLIPSIS
2594 **********************************************************************
2595 File "...", line 6, in newname
2596 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002597 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002598 >>> doctest.master = None # Reset master.
2599
Ezio Melotti13925002011-03-16 11:05:33 +02002600The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002601parameter:
2602
2603 >>> doctest.testfile('test_doctest.txt', report=False)
2604 ... # doctest: +ELLIPSIS
2605 **********************************************************************
2606 File "...", line 6, in test_doctest.txt
2607 Failed example:
2608 favorite_color
2609 Exception raised:
2610 ...
2611 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002612 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002613 >>> doctest.master = None # Reset master.
2614
2615The optional keyword argument `raise_on_error` can be used to raise an
2616exception on the first error (which may be useful for postmortem
2617debugging):
2618
2619 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2620 ... # doctest: +ELLIPSIS
2621 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002622 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002623 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002624
2625If the tests contain non-ASCII characters, the tests might fail, since
2626it's unknown which encoding is used. The encoding can be specified
2627using the optional keyword argument `encoding`:
2628
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002629 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002630 **********************************************************************
2631 File "...", line 7, in test_doctest4.txt
2632 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002633 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002634 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002635 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002636 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002637 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002638 **********************************************************************
2639 ...
2640 **********************************************************************
2641 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002642 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002643 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002644 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002645 >>> doctest.master = None # Reset master.
2646
2647 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002648 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002649 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002650
2651Test the verbose output:
2652
2653 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2654 Trying:
2655 'föö'
2656 Expecting:
2657 'f\xf6\xf6'
2658 ok
2659 Trying:
2660 'bÄ…r'
2661 Expecting:
2662 'b\u0105r'
2663 ok
2664 1 items passed all tests:
2665 2 tests in test_doctest4.txt
2666 2 tests in 1 items.
2667 2 passed and 0 failed.
2668 Test passed.
2669 TestResults(failed=0, attempted=2)
2670 >>> doctest.master = None # Reset master.
2671 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002672"""
2673
Peter Donise0b81012020-03-26 11:53:16 -04002674class TestImporter(importlib.abc.MetaPathFinder, importlib.abc.ResourceLoader):
2675
2676 def find_spec(self, fullname, path, target=None):
2677 return importlib.util.spec_from_file_location(fullname, path, loader=self)
2678
2679 def get_data(self, path):
2680 with open(path, mode='rb') as f:
2681 return f.read()
2682
2683class TestHook:
2684
2685 def __init__(self, pathdir):
2686 self.sys_path = sys.path[:]
2687 self.meta_path = sys.meta_path[:]
2688 self.path_hooks = sys.path_hooks[:]
2689 sys.path.append(pathdir)
2690 sys.path_importer_cache.clear()
2691 self.modules_before = sys.modules.copy()
2692 self.importer = TestImporter()
2693 sys.meta_path.append(self.importer)
2694
2695 def remove(self):
2696 sys.path[:] = self.sys_path
2697 sys.meta_path[:] = self.meta_path
2698 sys.path_hooks[:] = self.path_hooks
2699 sys.path_importer_cache.clear()
2700 sys.modules.clear()
2701 sys.modules.update(self.modules_before)
2702
2703
2704@contextlib.contextmanager
2705def test_hook(pathdir):
2706 hook = TestHook(pathdir)
2707 try:
2708 yield hook
2709 finally:
2710 hook.remove()
2711
2712
R David Murrayb48cb292014-10-02 22:42:42 -04002713def test_lineendings(): r"""
Peter Donise0b81012020-03-26 11:53:16 -04002714*nix systems use \n line endings, while Windows systems use \r\n, and
2715old Mac systems used \r, which Python still recognizes as a line ending. Python
R David Murrayb48cb292014-10-02 22:42:42 -04002716handles this using universal newline mode for reading files. Let's make
2717sure doctest does so (issue 8473) by creating temporary test files using each
Peter Donise0b81012020-03-26 11:53:16 -04002718of the three line disciplines. At least one will not match either the universal
2719newline \n or os.linesep for the platform the test is run on.
R David Murrayb48cb292014-10-02 22:42:42 -04002720
2721Windows line endings first:
2722
2723 >>> import tempfile, os
2724 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002725 >>> with open(fn, 'wb') as f:
2726 ... 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 -04002727 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002728 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002729 TestResults(failed=0, attempted=1)
2730 >>> os.remove(fn)
2731
2732And now *nix line endings:
2733
2734 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002735 >>> with open(fn, 'wb') as f:
2736 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002737 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002738 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002739 TestResults(failed=0, attempted=1)
2740 >>> os.remove(fn)
2741
Peter Donise0b81012020-03-26 11:53:16 -04002742And finally old Mac line endings:
2743
2744 >>> fn = tempfile.mktemp()
2745 >>> with open(fn, 'wb') as f:
2746 ... f.write(b'Test:\r\r >>> x = 1 + 1\r\rDone.\r')
2747 30
2748 >>> doctest.testfile(fn, module_relative=False, verbose=False)
2749 TestResults(failed=0, attempted=1)
2750 >>> os.remove(fn)
2751
2752Now we test with a package loader that has a get_data method, since that
2753bypasses the standard universal newline handling so doctest has to do the
2754newline conversion itself; let's make sure it does so correctly (issue 1812).
2755We'll write a file inside the package that has all three kinds of line endings
2756in it, and use a package hook to install a custom loader; on any platform,
2757at least one of the line endings will raise a ValueError for inconsistent
2758whitespace if doctest does not correctly do the newline conversion.
2759
2760 >>> dn = tempfile.mkdtemp()
2761 >>> pkg = os.path.join(dn, "doctest_testpkg")
2762 >>> os.mkdir(pkg)
Hai Shi46605972020-08-04 00:49:18 +08002763 >>> os_helper.create_empty_file(os.path.join(pkg, "__init__.py"))
Peter Donise0b81012020-03-26 11:53:16 -04002764 >>> fn = os.path.join(pkg, "doctest_testfile.txt")
2765 >>> with open(fn, 'wb') as f:
2766 ... f.write(
2767 ... b'Test:\r\n\r\n'
2768 ... b' >>> x = 1 + 1\r\n\r\n'
2769 ... b'Done.\r\n'
2770 ... b'Test:\n\n'
2771 ... b' >>> x = 1 + 1\n\n'
2772 ... b'Done.\n'
2773 ... b'Test:\r\r'
2774 ... b' >>> x = 1 + 1\r\r'
2775 ... b'Done.\r'
2776 ... )
2777 95
2778 >>> with test_hook(dn):
2779 ... doctest.testfile("doctest_testfile.txt", package="doctest_testpkg", verbose=False)
2780 TestResults(failed=0, attempted=3)
2781 >>> shutil.rmtree(dn)
2782
R David Murrayb48cb292014-10-02 22:42:42 -04002783"""
2784
R. David Murray58641de2009-06-12 15:33:19 +00002785def test_testmod(): r"""
2786Tests for the testmod function. More might be useful, but for now we're just
2787testing the case raised by Issue 6195, where trying to doctest a C module would
2788fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2789out of the binary module.
2790
2791 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002792 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002793 TestResults(failed=0, attempted=0)
2794"""
2795
Victor Stinner9d396392010-10-16 21:54:59 +00002796try:
2797 os.fsencode("foo-bär@baz.py")
2798except UnicodeEncodeError:
2799 # Skip the test: the filesystem encoding is unable to encode the filename
2800 pass
2801else:
2802 def test_unicode(): """
2803Check doctest with a non-ascii filename:
2804
2805 >>> doc = '''
2806 ... >>> raise Exception('clé')
2807 ... '''
2808 ...
2809 >>> parser = doctest.DocTestParser()
2810 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2811 >>> test
2812 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2813 >>> runner = doctest.DocTestRunner(verbose=False)
2814 >>> runner.run(test) # doctest: +ELLIPSIS
2815 **********************************************************************
2816 File "foo-bär@baz.py", line 2, in foo-bär@baz
2817 Failed example:
2818 raise Exception('clé')
2819 Exception raised:
2820 Traceback (most recent call last):
2821 File ...
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03002822 exec(compile(example.source, filename, "single",
Victor Stinner9d396392010-10-16 21:54:59 +00002823 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2824 raise Exception('clé')
2825 Exception: clé
2826 TestResults(failed=1, attempted=1)
2827 """
2828
R David Murray5707d502013-06-23 14:24:13 -04002829def test_CLI(): r"""
2830The doctest module can be used to run doctests against an arbitrary file.
2831These tests test this CLI functionality.
2832
2833We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002834to a temp dir to run the command against. Due to a current limitation in
2835script_helpers, though, we need a little utility function to turn the returned
2836output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002837
R David Murray4af68982013-06-25 08:11:22 -04002838 >>> def normalize(s):
2839 ... return '\n'.join(s.decode().splitlines())
2840
R David Murray4af68982013-06-25 08:11:22 -04002841With those preliminaries out of the way, we'll start with a file with two
2842simple tests and no errors. We'll run both the unadorned doctest command, and
2843the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002844
Hai Shi46605972020-08-04 00:49:18 +08002845 >>> from test.support import script_helper
2846 >>> from test.support.os_helper import temp_dir
Berker Peksagce643912015-05-06 06:33:17 +03002847 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002848 ... fn = os.path.join(tmpdir, 'myfile.doc')
2849 ... with open(fn, 'w') as f:
2850 ... _ = f.write('This is a very simple test file.\n')
2851 ... _ = f.write(' >>> 1 + 1\n')
2852 ... _ = f.write(' 2\n')
2853 ... _ = f.write(' >>> "a"\n')
2854 ... _ = f.write(" 'a'\n")
2855 ... _ = f.write('\n')
2856 ... _ = f.write('And that is it.\n')
2857 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002858 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002859 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002860 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002861
2862With no arguments and passing tests, we should get no output:
2863
2864 >>> rc1, out1, err1
2865 (0, b'', b'')
2866
2867With the verbose flag, we should see the test output, but no error output:
2868
2869 >>> rc2, err2
2870 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002871 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002872 Trying:
2873 1 + 1
2874 Expecting:
2875 2
2876 ok
2877 Trying:
2878 "a"
2879 Expecting:
2880 'a'
2881 ok
2882 1 items passed all tests:
2883 2 tests in myfile.doc
2884 2 tests in 1 items.
2885 2 passed and 0 failed.
2886 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002887
2888Now we'll write a couple files, one with three tests, the other a python module
2889with two tests, both of the files having "errors" in the tests that can be made
2890non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2891the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002892allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002893ability to process more than one file on the command line and, since the second
2894file ends in '.py', its handling of python module files (as opposed to straight
2895text files).
2896
Hai Shi46605972020-08-04 00:49:18 +08002897 >>> from test.support import script_helper
2898 >>> from test.support.os_helper import temp_dir
Berker Peksagce643912015-05-06 06:33:17 +03002899 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002900 ... fn = os.path.join(tmpdir, 'myfile.doc')
2901 ... with open(fn, 'w') as f:
2902 ... _ = f.write('This is another simple test file.\n')
2903 ... _ = f.write(' >>> 1 + 1\n')
2904 ... _ = f.write(' 2\n')
2905 ... _ = f.write(' >>> "abcdef"\n')
2906 ... _ = f.write(" 'a...f'\n")
2907 ... _ = f.write(' >>> "ajkml"\n')
2908 ... _ = f.write(" 'a...l'\n")
2909 ... _ = f.write('\n')
2910 ... _ = f.write('And that is it.\n')
2911 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2912 ... with open(fn2, 'w') as f:
2913 ... _ = f.write('def test_func():\n')
2914 ... _ = f.write(' \"\"\"\n')
2915 ... _ = f.write(' This is simple python test function.\n')
2916 ... _ = f.write(' >>> 1 + 1\n')
2917 ... _ = f.write(' 2\n')
2918 ... _ = f.write(' >>> "abc def"\n')
2919 ... _ = f.write(" 'abc def'\n")
2920 ... _ = f.write("\n")
2921 ... _ = f.write(' \"\"\"\n')
R David Murray5707d502013-06-23 14:24:13 -04002922 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002923 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002924 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002925 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002926 ... rc3, out3, err3 = script_helper.assert_python_ok(
2927 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002928 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002929 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002930 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002931 ... rc5, out5, err5 = script_helper.assert_python_ok(
2932 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002933 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002934
2935Our first test run will show the errors from the first file (doctest stops if a
2936file has errors). Note that doctest test-run error output appears on stdout,
2937not stderr:
2938
2939 >>> rc1, err1
2940 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002941 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002942 **********************************************************************
2943 File "...myfile.doc", line 4, in myfile.doc
2944 Failed example:
2945 "abcdef"
2946 Expected:
2947 'a...f'
2948 Got:
2949 'abcdef'
2950 **********************************************************************
2951 File "...myfile.doc", line 6, in myfile.doc
2952 Failed example:
2953 "ajkml"
2954 Expected:
2955 'a...l'
2956 Got:
2957 'ajkml'
2958 **********************************************************************
2959 1 items had failures:
2960 2 of 3 in myfile.doc
2961 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002962
2963With -o ELLIPSIS specified, the second run, against just the first file, should
2964produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2965should the third, which ran against both files:
2966
2967 >>> rc2, out2, err2
2968 (0, b'', b'')
2969 >>> rc3, out3, err3
2970 (0, b'', b'')
2971
2972The fourth run uses FAIL_FAST, so we should see only one error:
2973
2974 >>> rc4, err4
2975 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002976 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002977 **********************************************************************
2978 File "...myfile.doc", line 4, in myfile.doc
2979 Failed example:
2980 "abcdef"
2981 Expected:
2982 'a...f'
2983 Got:
2984 'abcdef'
2985 **********************************************************************
2986 1 items had failures:
2987 1 of 2 in myfile.doc
2988 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002989
2990The fifth test uses verbose with the two options, so we should get verbose
2991success output for the tests in both files:
2992
2993 >>> rc5, err5
2994 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002995 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002996 Trying:
2997 1 + 1
2998 Expecting:
2999 2
3000 ok
3001 Trying:
3002 "abcdef"
3003 Expecting:
3004 'a...f'
3005 ok
3006 Trying:
3007 "ajkml"
3008 Expecting:
3009 'a...l'
3010 ok
3011 1 items passed all tests:
3012 3 tests in myfile.doc
3013 3 tests in 1 items.
3014 3 passed and 0 failed.
3015 Test passed.
3016 Trying:
3017 1 + 1
3018 Expecting:
3019 2
3020 ok
3021 Trying:
3022 "abc def"
3023 Expecting:
3024 'abc def'
3025 ok
3026 1 items had no tests:
3027 myfile2
3028 1 items passed all tests:
3029 2 tests in myfile2.test_func
3030 2 tests in 2 items.
3031 2 passed and 0 failed.
3032 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04003033
3034We should also check some typical error cases.
3035
3036Invalid file name:
3037
3038 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03003039 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04003040 >>> rc, out
3041 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04003042 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003043 Traceback (most recent call last):
3044 ...
3045 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
3046
3047Invalid doctest option:
3048
3049 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03003050 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04003051 >>> rc, out
3052 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04003053 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003054 usage...invalid...nosuchoption...
3055
3056"""
3057
Sanyam Khuranacbb16452019-01-09 19:08:38 +05303058def test_no_trailing_whitespace_stripping():
3059 r"""
3060 The fancy reports had a bug for a long time where any trailing whitespace on
3061 the reported diff lines was stripped, making it impossible to see the
3062 differences in line reported as different that differed only in the amount of
3063 trailing whitespace. The whitespace still isn't particularly visible unless
3064 you use NDIFF, but at least it is now there to be found.
3065
3066 *NOTE*: This snippet was intentionally put inside a raw string to get rid of
3067 leading whitespace error in executing the example below
3068
3069 >>> def f(x):
3070 ... r'''
3071 ... >>> print('\n'.join(['a ', 'b']))
3072 ... a
3073 ... b
3074 ... '''
3075 """
3076 """
3077 *NOTE*: These doctest are not placed in raw string to depict the trailing whitespace
3078 using `\x20`
3079
3080 >>> test = doctest.DocTestFinder().find(f)[0]
3081 >>> flags = doctest.REPORT_NDIFF
3082 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
3083 ... # doctest: +ELLIPSIS
3084 **********************************************************************
3085 File ..., line 3, in f
3086 Failed example:
3087 print('\n'.join(['a ', 'b']))
3088 Differences (ndiff with -expected +actual):
3089 - a
3090 + a
3091 b
3092 TestResults(failed=1, attempted=1)
3093
3094 *NOTE*: `\x20` is for checking the trailing whitespace on the +a line above.
3095 We cannot use actual spaces there, as a commit hook prevents from committing
3096 patches that contain trailing whitespace. More info on Issue 24746.
3097 """
3098
Tim Peters8485b562004-08-04 18:46:34 +00003099######################################################################
3100## Main
3101######################################################################
3102
3103def test_main():
3104 # Check the doctest cases in doctest itself:
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02003105 ret = support.run_doctest(doctest, verbosity=True)
Victor Stinner931602a2016-03-25 12:48:17 +01003106
Tim Peters8485b562004-08-04 18:46:34 +00003107 # Check the doctest cases defined here:
3108 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003109 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00003110
Jason R. Coombsb9650a02018-03-05 18:29:08 -05003111 # Run unittests
3112 support.run_unittest(__name__)
3113
3114
Tim Peters8485b562004-08-04 18:46:34 +00003115def test_coverage(coverdir):
Hai Shi46605972020-08-04 00:49:18 +08003116 trace = import_helper.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01003117 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00003118 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00003119 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00003120 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003121 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00003122 r.write_results(show_missing=True, summary=True,
3123 coverdir=coverdir)
3124
3125if __name__ == '__main__':
3126 if '-c' in sys.argv:
3127 test_coverage('/tmp/doctest.cover')
3128 else:
3129 test_main()