blob: 3efe5dafc20ad14da32bbf5be11bc5d461005d44 [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Yury Selivanovb532df62014-12-08 15:00:05 -05007import functools
Victor Stinner9d396392010-10-16 21:54:59 +00008import os
Brett Cannon31f59292011-02-21 19:29:56 +00009import sys
Jason R. Coombsb9650a02018-03-05 18:29:08 -050010import importlib
Peter Donise0b81012020-03-26 11:53:16 -040011import importlib.abc
12import importlib.util
Jason R. Coombsb9650a02018-03-05 18:29:08 -050013import unittest
Nick Coghland5d9e022018-03-25 23:03:10 +100014import tempfile
Peter Donise0b81012020-03-26 11:53:16 -040015import shutil
16import contextlib
Florent Xiclunadc6f2d02010-04-02 19:25:32 +000017
Nick Coghlanf088e5e2008-12-14 11:50:48 +000018# NOTE: There are some additional tests relating to interaction with
19# zipimport in the test_zipimport_support test module.
20
Tim Peters8485b562004-08-04 18:46:34 +000021######################################################################
22## Sample Objects (used by test cases)
23######################################################################
24
25def sample_func(v):
26 """
Tim Peters19397e52004-08-06 22:02:59 +000027 Blah blah
28
Guido van Rossum7131f842007-02-09 20:13:25 +000029 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000030 44
Tim Peters19397e52004-08-06 22:02:59 +000031
32 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000033 """
34 return v+v
35
36class SampleClass:
37 """
Guido van Rossum7131f842007-02-09 20:13:25 +000038 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000039 1
Edward Loper4ae900f2004-09-21 03:20:34 +000040
41 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
42 >>>
43 ...
44
45 Multiline example:
46 >>> sc = SampleClass(3)
47 >>> for i in range(10):
48 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000049 ... print(' ', sc.get(), sep='', end='')
50 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000051 """
52 def __init__(self, val):
53 """
Guido van Rossum7131f842007-02-09 20:13:25 +000054 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000055 12
56 """
57 self.val = val
58
59 def double(self):
60 """
Guido van Rossum7131f842007-02-09 20:13:25 +000061 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000062 24
63 """
64 return SampleClass(self.val + self.val)
65
66 def get(self):
67 """
Guido van Rossum7131f842007-02-09 20:13:25 +000068 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000069 -5
70 """
71 return self.val
72
73 def a_staticmethod(v):
74 """
Guido van Rossum7131f842007-02-09 20:13:25 +000075 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000076 11
77 """
78 return v+1
79 a_staticmethod = staticmethod(a_staticmethod)
80
81 def a_classmethod(cls, v):
82 """
Guido van Rossum7131f842007-02-09 20:13:25 +000083 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000084 12
Guido van Rossum7131f842007-02-09 20:13:25 +000085 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000086 12
87 """
88 return v+2
89 a_classmethod = classmethod(a_classmethod)
90
91 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000092 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000093 22
94 """)
95
96 class NestedClass:
97 """
98 >>> x = SampleClass.NestedClass(5)
99 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +0000100 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +0000101 25
102 """
103 def __init__(self, val=0):
104 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000105 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +0000106 0
107 """
108 self.val = val
109 def square(self):
110 return SampleClass.NestedClass(self.val*self.val)
111 def get(self):
112 return self.val
113
114class SampleNewStyleClass(object):
115 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000116 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000117 1
118 2
119 3
120 """
121 def __init__(self, val):
122 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000123 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000124 12
125 """
126 self.val = val
127
128 def double(self):
129 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000130 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000131 24
132 """
133 return SampleNewStyleClass(self.val + self.val)
134
135 def get(self):
136 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000137 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000138 -5
139 """
140 return self.val
141
142######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000143## Fake stdin (for testing interactive debugging)
144######################################################################
145
146class _FakeInput:
147 """
148 A fake input stream for pdb's interactive debugger. Whenever a
149 line is read, print it (to simulate the user typing it), and then
150 return it. The set of lines to return is specified in the
151 constructor; they should not have trailing newlines.
152 """
153 def __init__(self, lines):
154 self.lines = lines
155
156 def readline(self):
157 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000158 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000159 return line+'\n'
160
161######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000162## Test Cases
163######################################################################
164
165def test_Example(): r"""
166Unit tests for the `Example` class.
167
Edward Lopera6b68322004-08-26 00:05:43 +0000168Example is a simple container class that holds:
169 - `source`: A source string.
170 - `want`: An expected output string.
171 - `exc_msg`: An expected exception message string (or None if no
172 exception is expected).
173 - `lineno`: A line number (within the docstring).
174 - `indent`: The example's indentation in the input string.
175 - `options`: An option dictionary, mapping option flags to True or
176 False.
Tim Peters8485b562004-08-04 18:46:34 +0000177
Edward Lopera6b68322004-08-26 00:05:43 +0000178These attributes are set by the constructor. `source` and `want` are
179required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000180
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000181 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000182 >>> (example.source, example.want, example.exc_msg,
183 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000184 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000185
186The first three attributes (`source`, `want`, and `exc_msg`) may be
187specified positionally; the remaining arguments should be specified as
188keyword arguments:
189
190 >>> exc_msg = 'IndexError: pop from an empty list'
191 >>> example = doctest.Example('[].pop()', '', exc_msg,
192 ... lineno=5, indent=4,
193 ... options={doctest.ELLIPSIS: True})
194 >>> (example.source, example.want, example.exc_msg,
195 ... example.lineno, example.indent, example.options)
196 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
197
198The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000199
Tim Petersbb431472004-08-09 03:51:46 +0000200 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000201 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000202 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000203 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000204
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000205 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000206 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000207 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000208
Tim Petersbb431472004-08-09 03:51:46 +0000209 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000210 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000211 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000212 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000213
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000214 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000215 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000216 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000217
Edward Lopera6b68322004-08-26 00:05:43 +0000218 Empty source string (which should never appear in real examples)
219 >>> e = doctest.Example('', '')
220 >>> e.source, e.want
221 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000222
Edward Lopera6b68322004-08-26 00:05:43 +0000223The constructor normalizes the `want` string to end in a newline,
224unless it's the empty string:
225
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000226 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000227 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000228 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000229
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000230 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000231 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000232 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000233
Edward Lopera6b68322004-08-26 00:05:43 +0000234 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000235 >>> e.source, e.want
236 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000237
238The constructor normalizes the `exc_msg` string to end in a newline,
239unless it's `None`:
240
241 Message spans one line
242 >>> exc_msg = 'IndexError: pop from an empty list'
243 >>> e = doctest.Example('[].pop()', '', exc_msg)
244 >>> e.exc_msg
245 'IndexError: pop from an empty list\n'
246
247 >>> exc_msg = 'IndexError: pop from an empty list\n'
248 >>> e = doctest.Example('[].pop()', '', exc_msg)
249 >>> e.exc_msg
250 'IndexError: pop from an empty list\n'
251
252 Message spans multiple lines
253 >>> exc_msg = 'ValueError: 1\n 2'
254 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
255 >>> e.exc_msg
256 'ValueError: 1\n 2\n'
257
258 >>> exc_msg = 'ValueError: 1\n 2\n'
259 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
260 >>> e.exc_msg
261 'ValueError: 1\n 2\n'
262
263 Empty (but non-None) exception message (which should never appear
264 in real examples)
265 >>> exc_msg = ''
266 >>> e = doctest.Example('raise X()', '', exc_msg)
267 >>> e.exc_msg
268 '\n'
Antoine Pitrou165b1282011-12-18 20:20:17 +0100269
270Compare `Example`:
271 >>> example = doctest.Example('print 1', '1\n')
272 >>> same_example = doctest.Example('print 1', '1\n')
273 >>> other_example = doctest.Example('print 42', '42\n')
274 >>> example == same_example
275 True
276 >>> example != same_example
277 False
278 >>> hash(example) == hash(same_example)
279 True
280 >>> example == other_example
281 False
282 >>> example != other_example
283 True
Tim Peters8485b562004-08-04 18:46:34 +0000284"""
285
286def test_DocTest(): r"""
287Unit tests for the `DocTest` class.
288
289DocTest is a collection of examples, extracted from a docstring, along
290with information about where the docstring comes from (a name,
291filename, and line number). The docstring is parsed by the `DocTest`
292constructor:
293
294 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000295 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000296 ... 12
297 ...
298 ... Non-example text.
299 ...
R David Murray44b548d2016-09-08 13:59:53 -0400300 ... >>> print('another\\example')
Tim Peters8485b562004-08-04 18:46:34 +0000301 ... another
302 ... example
303 ... '''
304 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000305 >>> parser = doctest.DocTestParser()
306 >>> test = parser.get_doctest(docstring, globs, 'some_test',
307 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000308 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000309 <DocTest some_test from some_file:20 (2 examples)>
310 >>> len(test.examples)
311 2
312 >>> e1, e2 = test.examples
313 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000314 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000315 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000316 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000317
318Source information (name, filename, and line number) is available as
319attributes on the doctest object:
320
321 >>> (test.name, test.filename, test.lineno)
322 ('some_test', 'some_file', 20)
323
324The line number of an example within its containing file is found by
325adding the line number of the example and the line number of its
326containing test:
327
328 >>> test.lineno + e1.lineno
329 21
330 >>> test.lineno + e2.lineno
331 26
332
Martin Panter46f50722016-05-26 05:35:26 +0000333If the docstring contains inconsistent leading whitespace in the
Tim Peters8485b562004-08-04 18:46:34 +0000334expected output of an example, then `DocTest` will raise a ValueError:
335
336 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000337 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000338 ... bad
339 ... indentation
340 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000341 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000342 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000343 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000344
345If the docstring contains inconsistent leading whitespace on
346continuation lines, then `DocTest` will raise a ValueError:
347
348 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000349 ... >>> print(('bad indentation',
350 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000351 ... ('bad', 'indentation')
352 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000353 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000354 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000355 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000356
357If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
358will raise a ValueError:
359
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000360 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000361 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000362 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000363 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000364
365If there's no blank space after a PS2 prompt ('...'), then `DocTest`
366will raise a ValueError:
367
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000368 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000369 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000370 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000371 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000372
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100373Compare `DocTest`:
374
375 >>> docstring = '''
376 ... >>> print 12
377 ... 12
378 ... '''
379 >>> test = parser.get_doctest(docstring, globs, 'some_test',
380 ... 'some_test', 20)
381 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
382 ... 'some_test', 20)
383 >>> test == same_test
384 True
385 >>> test != same_test
386 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100387 >>> hash(test) == hash(same_test)
388 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100389 >>> docstring = '''
390 ... >>> print 42
391 ... 42
392 ... '''
393 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
394 ... 'other_file', 10)
395 >>> test == other_test
396 False
397 >>> test != other_test
398 True
399
400Compare `DocTestCase`:
401
402 >>> DocTestCase = doctest.DocTestCase
403 >>> test_case = DocTestCase(test)
404 >>> same_test_case = DocTestCase(same_test)
405 >>> other_test_case = DocTestCase(other_test)
406 >>> test_case == same_test_case
407 True
408 >>> test_case != same_test_case
409 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100410 >>> hash(test_case) == hash(same_test_case)
411 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100412 >>> test == other_test_case
413 False
414 >>> test != other_test_case
415 True
416
Tim Peters8485b562004-08-04 18:46:34 +0000417"""
418
Zachary Ware7119b452013-11-24 02:21:57 -0600419class test_DocTestFinder:
420 def basics(): r"""
Tim Peters8485b562004-08-04 18:46:34 +0000421Unit tests for the `DocTestFinder` class.
422
423DocTestFinder is used to extract DocTests from an object's docstring
424and the docstrings of its contained objects. It can be used with
425modules, functions, classes, methods, staticmethods, classmethods, and
426properties.
427
428Finding Tests in Functions
429~~~~~~~~~~~~~~~~~~~~~~~~~~
430For a function whose docstring contains examples, DocTestFinder.find()
431will return a single test (for that function's docstring):
432
Tim Peters8485b562004-08-04 18:46:34 +0000433 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000434
435We'll simulate a __file__ attr that ends in pyc:
436
437 >>> import test.test_doctest
438 >>> old = test.test_doctest.__file__
439 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
440
Tim Peters8485b562004-08-04 18:46:34 +0000441 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000442
Guido van Rossum7131f842007-02-09 20:13:25 +0000443 >>> print(tests) # doctest: +ELLIPSIS
Peter Donise0b81012020-03-26 11:53:16 -0400444 [<DocTest sample_func from ...:25 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000445
Tim Peters4de7c5c2004-08-23 22:38:05 +0000446The exact name depends on how test_doctest was invoked, so allow for
447leading path components.
448
449 >>> tests[0].filename # doctest: +ELLIPSIS
450 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000451
452 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000453
Jim Fulton07a349c2004-08-22 14:10:00 +0000454
Tim Peters8485b562004-08-04 18:46:34 +0000455 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000456 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000457 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000458
Edward Loper32ddbf72004-09-13 05:47:24 +0000459By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000460
461 >>> def no_docstring(v):
462 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000463 >>> finder.find(no_docstring)
464 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000465
466However, the optional argument `exclude_empty` to the DocTestFinder
467constructor can be used to exclude tests for objects with empty
468docstrings:
469
470 >>> def no_docstring(v):
471 ... pass
472 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
473 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000474 []
475
476If the function has a docstring with no examples, then a test with no
477examples is returned. (This lets `DocTestRunner` collect statistics
478about which functions have no tests -- but is that useful? And should
479an empty test also be created when there's no docstring?)
480
481 >>> def no_examples(v):
482 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000483 >>> finder.find(no_examples) # doctest: +ELLIPSIS
484 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000485
486Finding Tests in Classes
487~~~~~~~~~~~~~~~~~~~~~~~~
488For a class, DocTestFinder will create a test for the class's
489docstring, and will recursively explore its contents, including
490methods, classmethods, staticmethods, properties, and nested classes.
491
492 >>> finder = doctest.DocTestFinder()
493 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000494 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000495 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000496 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000497 3 SampleClass.NestedClass
498 1 SampleClass.NestedClass.__init__
499 1 SampleClass.__init__
500 2 SampleClass.a_classmethod
501 1 SampleClass.a_property
502 1 SampleClass.a_staticmethod
503 1 SampleClass.double
504 1 SampleClass.get
505
506New-style classes are also supported:
507
508 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000509 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000510 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000511 1 SampleNewStyleClass
512 1 SampleNewStyleClass.__init__
513 1 SampleNewStyleClass.double
514 1 SampleNewStyleClass.get
515
516Finding Tests in Modules
517~~~~~~~~~~~~~~~~~~~~~~~~
518For a module, DocTestFinder will create a test for the class's
519docstring, and will recursively explore its contents, including
520functions, classes, and the `__test__` dictionary, if it exists:
521
522 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000523 >>> import types
524 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000525 >>> def triple(val):
526 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000527 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000528 ... 33
529 ... '''
530 ... return val*3
531 >>> m.__dict__.update({
532 ... 'sample_func': sample_func,
533 ... 'SampleClass': SampleClass,
534 ... '__doc__': '''
535 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000536 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000537 ... module
538 ... ''',
539 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000540 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000541 ... 'c': triple}})
542
543 >>> finder = doctest.DocTestFinder()
544 >>> # Use module=test.test_doctest, to prevent doctest from
545 >>> # ignoring the objects since they weren't defined in m.
546 >>> import test.test_doctest
547 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000548 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000549 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000550 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000551 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000552 3 some_module.SampleClass.NestedClass
553 1 some_module.SampleClass.NestedClass.__init__
554 1 some_module.SampleClass.__init__
555 2 some_module.SampleClass.a_classmethod
556 1 some_module.SampleClass.a_property
557 1 some_module.SampleClass.a_staticmethod
558 1 some_module.SampleClass.double
559 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000560 1 some_module.__test__.c
561 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000562 1 some_module.sample_func
563
564Duplicate Removal
565~~~~~~~~~~~~~~~~~
566If a single object is listed twice (under different names), then tests
567will only be generated for it once:
568
Tim Petersf3f57472004-08-08 06:11:48 +0000569 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000570 >>> assert doctest_aliases.TwoNames.f
571 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000572 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000573 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000574 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000575 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000576 test.doctest_aliases.TwoNames
577
578 TwoNames.f and TwoNames.g are bound to the same object.
579 We can't guess which will be found in doctest's traversal of
580 TwoNames.__dict__ first, so we have to allow for either.
581
582 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000583 True
584
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000585Empty Tests
586~~~~~~~~~~~
587By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000588
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000589 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000590 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000591 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000592 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000593 3 SampleClass.NestedClass
594 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000595 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000596 2 SampleClass.a_classmethod
597 1 SampleClass.a_property
598 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000599 1 SampleClass.double
600 1 SampleClass.get
601
602By default, that excluded objects with no doctests. exclude_empty=False
603tells it to include (empty) tests for objects with no doctests. This feature
604is really to support backward compatibility in what doctest.master.summarize()
605displays.
606
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000607 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000608 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000609 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000610 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000611 3 SampleClass.NestedClass
612 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000613 0 SampleClass.NestedClass.get
614 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000615 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000616 2 SampleClass.a_classmethod
617 1 SampleClass.a_property
618 1 SampleClass.a_staticmethod
619 1 SampleClass.double
620 1 SampleClass.get
621
Tim Peters8485b562004-08-04 18:46:34 +0000622Turning off Recursion
623~~~~~~~~~~~~~~~~~~~~~
624DocTestFinder can be told not to look for tests in contained objects
625using the `recurse` flag:
626
627 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000628 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000629 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000630 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000631
632Line numbers
633~~~~~~~~~~~~
634DocTestFinder finds the line number of each example:
635
636 >>> def f(x):
637 ... '''
638 ... >>> x = 12
639 ...
640 ... some text
641 ...
642 ... >>> # examples are not created for comments & bare prompts.
643 ... >>>
644 ... ...
645 ...
646 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000647 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000648 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000649 ... >>> x//2
650 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000651 ... '''
652 >>> test = doctest.DocTestFinder().find(f)[0]
653 >>> [e.lineno for e in test.examples]
654 [1, 9, 12]
Zachary Ware7119b452013-11-24 02:21:57 -0600655"""
656
657 if int.__doc__: # simple check for --without-doc-strings, skip if lacking
658 def non_Python_modules(): r"""
Zachary Warea4b7a752013-11-24 01:19:09 -0600659
660Finding Doctests in Modules Not Written in Python
661~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
662DocTestFinder can also find doctests in most modules not written in Python.
663We'll use builtins as an example, since it almost certainly isn't written in
664plain ol' Python and is guaranteed to be available.
665
666 >>> import builtins
667 >>> tests = doctest.DocTestFinder().find(builtins)
sweeneydea81849b2020-04-22 17:05:48 -0400668 >>> 816 < len(tests) < 836 # approximate number of objects with docstrings
Zachary Ware7119b452013-11-24 02:21:57 -0600669 True
Zachary Warea4b7a752013-11-24 01:19:09 -0600670 >>> real_tests = [t for t in tests if len(t.examples) > 0]
Zachary Ware7119b452013-11-24 02:21:57 -0600671 >>> len(real_tests) # objects that actually have doctests
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -0700672 13
Zachary Warea4b7a752013-11-24 01:19:09 -0600673 >>> for t in real_tests:
674 ... print('{} {}'.format(len(t.examples), t.name))
675 ...
676 1 builtins.bin
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700677 5 builtins.bytearray.hex
678 5 builtins.bytes.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600679 3 builtins.float.as_integer_ratio
680 2 builtins.float.fromhex
681 2 builtins.float.hex
682 1 builtins.hex
683 1 builtins.int
Lisa Roach5ac70432018-09-13 23:56:23 -0700684 3 builtins.int.as_integer_ratio
Zachary Warea4b7a752013-11-24 01:19:09 -0600685 2 builtins.int.bit_length
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700686 5 builtins.memoryview.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600687 1 builtins.oct
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -0700688 1 builtins.zip
Zachary Warea4b7a752013-11-24 01:19:09 -0600689
690Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
691'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
692and 'int' is a type.
Tim Peters8485b562004-08-04 18:46:34 +0000693"""
694
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500695
696class TestDocTestFinder(unittest.TestCase):
697
698 def test_empty_namespace_package(self):
699 pkg_name = 'doctest_empty_pkg'
Nick Coghland5d9e022018-03-25 23:03:10 +1000700 with tempfile.TemporaryDirectory() as parent_dir:
701 pkg_dir = os.path.join(parent_dir, pkg_name)
702 os.mkdir(pkg_dir)
703 sys.path.append(parent_dir)
704 try:
705 mod = importlib.import_module(pkg_name)
706 finally:
707 support.forget(pkg_name)
708 sys.path.pop()
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500709
Xtreak8289e272019-12-13 23:36:53 +0530710 include_empty_finder = doctest.DocTestFinder(exclude_empty=False)
711 exclude_empty_finder = doctest.DocTestFinder(exclude_empty=True)
712
713 self.assertEqual(len(include_empty_finder.find(mod)), 1)
714 self.assertEqual(len(exclude_empty_finder.find(mod)), 0)
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500715
Edward Loper00f8da72004-08-26 18:05:07 +0000716def test_DocTestParser(): r"""
717Unit tests for the `DocTestParser` class.
718
719DocTestParser is used to parse docstrings containing doctest examples.
720
721The `parse` method divides a docstring into examples and intervening
722text:
723
724 >>> s = '''
725 ... >>> x, y = 2, 3 # no output expected
726 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000727 ... ... print(x)
728 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000729 ... 2
730 ... 3
731 ...
732 ... Some text.
733 ... >>> x+y
734 ... 5
735 ... '''
736 >>> parser = doctest.DocTestParser()
737 >>> for piece in parser.parse(s):
738 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000739 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000740 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000741 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000742 Text: '\n'
743 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
744 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000745 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000746 Text: '\nSome text.\n'
747 Example: ('x+y\n', '5\n', 9)
748 Text: ''
749
750The `get_examples` method returns just the examples:
751
752 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000753 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000754 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000755 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000756 ('x+y\n', '5\n', 9)
757
758The `get_doctest` method creates a Test from the examples, along with the
759given arguments:
760
761 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
762 >>> (test.name, test.filename, test.lineno)
763 ('name', 'filename', 5)
764 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000765 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000766 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000767 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000768 ('x+y\n', '5\n', 9)
769"""
770
Tim Peters8485b562004-08-04 18:46:34 +0000771class test_DocTestRunner:
772 def basics(): r"""
773Unit tests for the `DocTestRunner` class.
774
775DocTestRunner is used to run DocTest test cases, and to accumulate
776statistics. Here's a simple DocTest case we can use:
777
778 >>> def f(x):
779 ... '''
780 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000781 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000782 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000783 ... >>> x//2
784 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000785 ... '''
786 >>> test = doctest.DocTestFinder().find(f)[0]
787
788The main DocTestRunner interface is the `run` method, which runs a
789given DocTest case in a given namespace (globs). It returns a tuple
790`(f,t)`, where `f` is the number of failed tests and `t` is the number
791of tried tests.
792
793 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000794 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000795
796If any example produces incorrect output, then the test runner reports
797the failure and proceeds to the next example:
798
799 >>> def f(x):
800 ... '''
801 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000802 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000803 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000804 ... >>> x//2
805 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000806 ... '''
807 >>> test = doctest.DocTestFinder().find(f)[0]
808 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000809 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000810 Trying:
811 x = 12
812 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000813 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000814 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000815 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000816 Expecting:
817 14
Tim Peters8485b562004-08-04 18:46:34 +0000818 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000819 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000820 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000821 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000822 Expected:
823 14
824 Got:
825 12
Edward Loperaacf0832004-08-26 01:19:50 +0000826 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000827 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000828 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000829 6
Tim Peters8485b562004-08-04 18:46:34 +0000830 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000831 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000832"""
833 def verbose_flag(): r"""
834The `verbose` flag makes the test runner generate more detailed
835output:
836
837 >>> def f(x):
838 ... '''
839 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000840 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000841 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000842 ... >>> x//2
843 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000844 ... '''
845 >>> test = doctest.DocTestFinder().find(f)[0]
846
847 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000848 Trying:
849 x = 12
850 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000851 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000852 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000853 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000854 Expecting:
855 12
Tim Peters8485b562004-08-04 18:46:34 +0000856 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000857 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000858 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000859 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000860 6
Tim Peters8485b562004-08-04 18:46:34 +0000861 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000862 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000863
864If the `verbose` flag is unspecified, then the output will be verbose
865iff `-v` appears in sys.argv:
866
867 >>> # Save the real sys.argv list.
868 >>> old_argv = sys.argv
869
870 >>> # If -v does not appear in sys.argv, then output isn't verbose.
871 >>> sys.argv = ['test']
872 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000873 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000874
875 >>> # If -v does appear in sys.argv, then output is verbose.
876 >>> sys.argv = ['test', '-v']
877 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000878 Trying:
879 x = 12
880 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000881 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000882 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000883 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000884 Expecting:
885 12
Tim Peters8485b562004-08-04 18:46:34 +0000886 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000887 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000888 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000889 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000890 6
Tim Peters8485b562004-08-04 18:46:34 +0000891 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000892 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000893
894 >>> # Restore sys.argv
895 >>> sys.argv = old_argv
896
897In the remaining examples, the test runner's verbosity will be
898explicitly set, to ensure that the test behavior is consistent.
899 """
900 def exceptions(): r"""
901Tests of `DocTestRunner`'s exception handling.
902
903An expected exception is specified with a traceback message. The
904lines between the first line and the type/value may be omitted or
905replaced with any other string:
906
907 >>> def f(x):
908 ... '''
909 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000910 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000911 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000912 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000913 ... '''
914 >>> test = doctest.DocTestFinder().find(f)[0]
915 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000916 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000917
Edward Loper19b19582004-08-25 23:07:03 +0000918An example may not generate output before it raises an exception; if
919it does, then the traceback message will not be recognized as
920signaling an expected exception, so the example will be reported as an
921unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000922
923 >>> def f(x):
924 ... '''
925 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000926 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000927 ... pre-exception output
928 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000929 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000930 ... '''
931 >>> test = doctest.DocTestFinder().find(f)[0]
932 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000933 ... # doctest: +ELLIPSIS
934 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000935 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000936 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000937 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000938 Exception raised:
939 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000940 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000941 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000942
943Exception messages may contain newlines:
944
945 >>> def f(x):
946 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000947 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000948 ... Traceback (most recent call last):
949 ... ValueError: multi
950 ... line
951 ... message
952 ... '''
953 >>> test = doctest.DocTestFinder().find(f)[0]
954 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000955 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000956
957If an exception is expected, but an exception with the wrong type or
958message is raised, then it is reported as a failure:
959
960 >>> def f(x):
961 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000962 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000963 ... Traceback (most recent call last):
964 ... ValueError: wrong message
965 ... '''
966 >>> test = doctest.DocTestFinder().find(f)[0]
967 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000968 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000969 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000970 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000971 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000972 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000973 Expected:
974 Traceback (most recent call last):
975 ValueError: wrong message
976 Got:
977 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000978 ...
Tim Peters8485b562004-08-04 18:46:34 +0000979 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000980 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000981
Tim Peters1fbf9c52004-09-04 17:21:02 +0000982However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
983detail:
984
985 >>> def f(x):
986 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000987 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000988 ... Traceback (most recent call last):
989 ... ValueError: wrong message
990 ... '''
991 >>> test = doctest.DocTestFinder().find(f)[0]
992 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000993 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000994
Nick Coghlan5e76e942010-06-12 13:42:46 +0000995IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
996between Python versions. For example, in Python 2.x, the module path of
997the exception is not in the output, but this will fail under Python 3:
998
999 >>> def f(x):
1000 ... r'''
1001 ... >>> from http.client import HTTPException
1002 ... >>> raise HTTPException('message')
1003 ... Traceback (most recent call last):
1004 ... HTTPException: message
1005 ... '''
1006 >>> test = doctest.DocTestFinder().find(f)[0]
1007 >>> doctest.DocTestRunner(verbose=False).run(test)
1008 ... # doctest: +ELLIPSIS
1009 **********************************************************************
1010 File ..., line 4, in f
1011 Failed example:
1012 raise HTTPException('message')
1013 Expected:
1014 Traceback (most recent call last):
1015 HTTPException: message
1016 Got:
1017 Traceback (most recent call last):
1018 ...
1019 http.client.HTTPException: message
1020 TestResults(failed=1, attempted=2)
1021
1022But in Python 3 the module path is included, and therefore a test must look
1023like the following test to succeed in Python 3. But that test will fail under
1024Python 2.
1025
1026 >>> def f(x):
1027 ... r'''
1028 ... >>> from http.client import HTTPException
1029 ... >>> raise HTTPException('message')
1030 ... Traceback (most recent call last):
1031 ... http.client.HTTPException: message
1032 ... '''
1033 >>> test = doctest.DocTestFinder().find(f)[0]
1034 >>> doctest.DocTestRunner(verbose=False).run(test)
1035 TestResults(failed=0, attempted=2)
1036
1037However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1038(or its unexpected absence) will be ignored:
1039
1040 >>> def f(x):
1041 ... r'''
1042 ... >>> from http.client import HTTPException
1043 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1044 ... Traceback (most recent call last):
1045 ... HTTPException: message
1046 ... '''
1047 >>> test = doctest.DocTestFinder().find(f)[0]
1048 >>> doctest.DocTestRunner(verbose=False).run(test)
1049 TestResults(failed=0, attempted=2)
1050
1051The module path will be completely ignored, so two different module paths will
1052still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1053be used when exceptions have changed module.
1054
1055 >>> def f(x):
1056 ... r'''
1057 ... >>> from http.client import HTTPException
1058 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1059 ... Traceback (most recent call last):
1060 ... foo.bar.HTTPException: message
1061 ... '''
1062 >>> test = doctest.DocTestFinder().find(f)[0]
1063 >>> doctest.DocTestRunner(verbose=False).run(test)
1064 TestResults(failed=0, attempted=2)
1065
Tim Peters1fbf9c52004-09-04 17:21:02 +00001066But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1067
1068 >>> def f(x):
1069 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001070 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001071 ... Traceback (most recent call last):
1072 ... TypeError: wrong type
1073 ... '''
1074 >>> test = doctest.DocTestFinder().find(f)[0]
1075 >>> doctest.DocTestRunner(verbose=False).run(test)
1076 ... # doctest: +ELLIPSIS
1077 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001078 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001079 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001080 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001081 Expected:
1082 Traceback (most recent call last):
1083 TypeError: wrong type
1084 Got:
1085 Traceback (most recent call last):
1086 ...
1087 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001088 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001089
Tim Petersf9a07f22013-12-03 21:02:05 -06001090If the exception does not have a message, you can still use
1091IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1092
1093 >>> def f(x):
1094 ... r'''
1095 ... >>> from http.client import HTTPException
1096 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1097 ... Traceback (most recent call last):
1098 ... foo.bar.HTTPException
1099 ... '''
1100 >>> test = doctest.DocTestFinder().find(f)[0]
1101 >>> doctest.DocTestRunner(verbose=False).run(test)
1102 TestResults(failed=0, attempted=2)
1103
1104Note that a trailing colon doesn't matter either:
1105
1106 >>> def f(x):
1107 ... r'''
1108 ... >>> from http.client import HTTPException
1109 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1110 ... Traceback (most recent call last):
1111 ... foo.bar.HTTPException:
1112 ... '''
1113 >>> test = doctest.DocTestFinder().find(f)[0]
1114 >>> doctest.DocTestRunner(verbose=False).run(test)
1115 TestResults(failed=0, attempted=2)
1116
Tim Peters8485b562004-08-04 18:46:34 +00001117If an exception is raised but not expected, then it is reported as an
1118unexpected exception:
1119
Tim Peters8485b562004-08-04 18:46:34 +00001120 >>> def f(x):
1121 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001122 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001123 ... 0
1124 ... '''
1125 >>> test = doctest.DocTestFinder().find(f)[0]
1126 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001127 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001128 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001129 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001130 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001131 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001132 Exception raised:
1133 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001134 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001135 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001136 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001137"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001138 def displayhook(): r"""
1139Test that changing sys.displayhook doesn't matter for doctest.
1140
1141 >>> import sys
1142 >>> orig_displayhook = sys.displayhook
1143 >>> def my_displayhook(x):
1144 ... print('hi!')
1145 >>> sys.displayhook = my_displayhook
1146 >>> def f():
1147 ... '''
1148 ... >>> 3
1149 ... 3
1150 ... '''
1151 >>> test = doctest.DocTestFinder().find(f)[0]
1152 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1153 >>> post_displayhook = sys.displayhook
1154
1155 We need to restore sys.displayhook now, so that we'll be able to test
1156 results.
1157
1158 >>> sys.displayhook = orig_displayhook
1159
1160 Ok, now we can check that everything is ok.
1161
1162 >>> r
1163 TestResults(failed=0, attempted=1)
1164 >>> post_displayhook is my_displayhook
1165 True
1166"""
Tim Peters8485b562004-08-04 18:46:34 +00001167 def optionflags(): r"""
1168Tests of `DocTestRunner`'s option flag handling.
1169
1170Several option flags can be used to customize the behavior of the test
1171runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001172to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001173together).
1174
1175The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1176and 1/0:
1177
1178 >>> def f(x):
1179 ... '>>> True\n1\n'
1180
1181 >>> # Without the flag:
1182 >>> test = doctest.DocTestFinder().find(f)[0]
1183 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001184 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001185
1186 >>> # With the flag:
1187 >>> test = doctest.DocTestFinder().find(f)[0]
1188 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1189 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001190 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001191 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001192 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001193 Failed example:
1194 True
1195 Expected:
1196 1
1197 Got:
1198 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001199 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001200
1201The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1202and the '<BLANKLINE>' marker:
1203
1204 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001205 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001206
1207 >>> # Without the flag:
1208 >>> test = doctest.DocTestFinder().find(f)[0]
1209 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001210 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001211
1212 >>> # With the flag:
1213 >>> test = doctest.DocTestFinder().find(f)[0]
1214 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1215 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001216 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001217 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001218 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001219 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001220 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001221 Expected:
1222 a
1223 <BLANKLINE>
1224 b
1225 Got:
1226 a
1227 <BLANKLINE>
1228 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001229 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001230
1231The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1232treated as equal:
1233
1234 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001235 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001236
1237 >>> # Without the flag:
1238 >>> test = doctest.DocTestFinder().find(f)[0]
1239 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001240 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001241 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001242 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001243 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001244 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001245 Expected:
1246 1 2
1247 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001248 Got:
1249 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001250 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001251
1252 >>> # With the flag:
1253 >>> test = doctest.DocTestFinder().find(f)[0]
1254 >>> flags = doctest.NORMALIZE_WHITESPACE
1255 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001256 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001257
Tim Peters026f8dc2004-08-19 16:38:58 +00001258 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001259 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001260 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1261 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1262
Tim Peters8485b562004-08-04 18:46:34 +00001263The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1264output to match any substring in the actual output:
1265
1266 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001267 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001268
1269 >>> # Without the flag:
1270 >>> test = doctest.DocTestFinder().find(f)[0]
1271 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001272 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001273 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001274 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001275 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001276 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001277 Expected:
1278 [0, 1, 2, ..., 14]
1279 Got:
1280 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001281 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001282
1283 >>> # With the flag:
1284 >>> test = doctest.DocTestFinder().find(f)[0]
1285 >>> flags = doctest.ELLIPSIS
1286 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001287 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001288
Tim Peterse594bee2004-08-22 01:47:51 +00001289 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001290
Guido van Rossume0192e52007-02-09 23:39:59 +00001291 >>> if 1:
1292 ... for i in range(100):
1293 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1294 ... print('!')
1295 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001296
Tim Peters026f8dc2004-08-19 16:38:58 +00001297 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001298
Guido van Rossume0192e52007-02-09 23:39:59 +00001299 >>> if 1: #doctest: +ELLIPSIS
1300 ... for i in range(20):
1301 ... print(i, end=' ')
1302 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001303 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001304
Tim Peters026f8dc2004-08-19 16:38:58 +00001305 Examples from the docs:
1306
Guido van Rossum805365e2007-05-07 22:24:25 +00001307 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001308 [0, 1, ..., 18, 19]
1309
Guido van Rossum805365e2007-05-07 22:24:25 +00001310 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001311 ... # doctest: +NORMALIZE_WHITESPACE
1312 [0, 1, ..., 18, 19]
1313
Thomas Wouters477c8d52006-05-27 19:21:47 +00001314The SKIP flag causes an example to be skipped entirely. I.e., the
1315example is not run. It can be useful in contexts where doctest
1316examples serve as both documentation and test cases, and an example
1317should be included for documentation purposes, but should not be
1318checked (e.g., because its output is random, or depends on resources
1319which would be unavailable.) The SKIP flag can also be used for
1320'commenting out' broken examples.
1321
1322 >>> import unavailable_resource # doctest: +SKIP
1323 >>> unavailable_resource.do_something() # doctest: +SKIP
1324 >>> unavailable_resource.blow_up() # doctest: +SKIP
1325 Traceback (most recent call last):
1326 ...
1327 UncheckedBlowUpError: Nobody checks me.
1328
1329 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001330 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001331 0.721216923889
1332
Edward Loper71f55af2004-08-26 01:41:51 +00001333The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001334and actual outputs to be displayed using a unified diff:
1335
1336 >>> def f(x):
1337 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001338 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001339 ... a
1340 ... B
1341 ... c
1342 ... d
1343 ... f
1344 ... g
1345 ... h
1346 ... '''
1347
1348 >>> # Without the flag:
1349 >>> test = doctest.DocTestFinder().find(f)[0]
1350 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001351 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001352 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001353 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001354 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001355 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001356 Expected:
1357 a
1358 B
1359 c
1360 d
1361 f
1362 g
1363 h
1364 Got:
1365 a
1366 b
1367 c
1368 d
1369 e
1370 f
1371 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001372 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001373
1374 >>> # With the flag:
1375 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001376 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001377 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001378 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001379 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001380 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001381 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001382 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001383 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001384 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001385 a
1386 -B
1387 +b
1388 c
1389 d
1390 +e
1391 f
1392 g
1393 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001394 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001395
Edward Loper71f55af2004-08-26 01:41:51 +00001396The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001397and actual outputs to be displayed using a context diff:
1398
Edward Loper71f55af2004-08-26 01:41:51 +00001399 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001400 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001401 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001402 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001403 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001404 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001405 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001406 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001407 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001408 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001409 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001410 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001411 a
1412 ! B
1413 c
1414 d
1415 f
1416 g
1417 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001418 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001419 a
1420 ! b
1421 c
1422 d
1423 + e
1424 f
1425 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001426 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001427
1428
Edward Loper71f55af2004-08-26 01:41:51 +00001429The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001430used by the popular ndiff.py utility. This does intraline difference
1431marking, as well as interline differences.
1432
1433 >>> def f(x):
1434 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001435 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001436 ... a b c d e f g h i j k 1 m
1437 ... '''
1438 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001439 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001440 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001441 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001442 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001443 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001444 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001445 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001446 Differences (ndiff with -expected +actual):
1447 - a b c d e f g h i j k 1 m
1448 ? ^
1449 + a b c d e f g h i j k l m
1450 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001451 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001452
Ezio Melotti13925002011-03-16 11:05:33 +02001453The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001454failing example:
1455
1456 >>> def f(x):
1457 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001458 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001459 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001460 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001461 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001462 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001463 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001464 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001465 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001466 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001467 ... 500
1468 ... '''
1469 >>> test = doctest.DocTestFinder().find(f)[0]
1470 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1471 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001472 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001473 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001474 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001475 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001476 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001477 Expected:
1478 200
1479 Got:
1480 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001481 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001482
Ezio Melotti13925002011-03-16 11:05:33 +02001483However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001484
1485 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001486 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001487 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001488 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001489 Expecting:
1490 1
1491 ok
1492 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001493 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001494 Expecting:
1495 200
1496 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001497 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001498 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001499 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001500 Expected:
1501 200
1502 Got:
1503 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001504 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001505
R David Murray5a9d7062012-11-21 15:09:21 -05001506The FAIL_FAST flag causes the runner to exit after the first failing example,
1507so subsequent examples are not even attempted:
1508
1509 >>> flags = doctest.FAIL_FAST
1510 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1511 ... # doctest: +ELLIPSIS
1512 **********************************************************************
1513 File ..., line 5, in f
1514 Failed example:
1515 print(2) # first failure
1516 Expected:
1517 200
1518 Got:
1519 2
1520 TestResults(failed=1, attempted=2)
1521
1522Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1523FAIL_FAST only:
1524
1525 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1526 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1527 ... # doctest: +ELLIPSIS
1528 **********************************************************************
1529 File ..., line 5, in f
1530 Failed example:
1531 print(2) # first failure
1532 Expected:
1533 200
1534 Got:
1535 2
1536 TestResults(failed=1, attempted=2)
1537
1538For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1539exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001540
1541 >>> def f(x):
1542 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001543 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001544 ... 1
1545 ... >>> raise ValueError(2) # first failure
1546 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001547 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001548 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001549 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001550 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001551 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001552 ... 500
1553 ... '''
1554 >>> test = doctest.DocTestFinder().find(f)[0]
1555 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1556 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1557 ... # doctest: +ELLIPSIS
1558 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001559 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001560 Failed example:
1561 raise ValueError(2) # first failure
1562 Exception raised:
1563 ...
1564 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001565 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001566 >>> flags = doctest.FAIL_FAST
1567 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1568 ... # doctest: +ELLIPSIS
1569 **********************************************************************
1570 File ..., line 5, in f
1571 Failed example:
1572 raise ValueError(2) # first failure
1573 Exception raised:
1574 ...
1575 ValueError: 2
1576 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001577
Thomas Wouters477c8d52006-05-27 19:21:47 +00001578New option flags can also be registered, via register_optionflag(). Here
1579we reach into doctest's internals a bit.
1580
1581 >>> unlikely = "UNLIKELY_OPTION_NAME"
1582 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1583 False
1584 >>> new_flag_value = doctest.register_optionflag(unlikely)
1585 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1586 True
1587
1588Before 2.4.4/2.5, registering a name more than once erroneously created
1589more than one flag value. Here we verify that's fixed:
1590
1591 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1592 >>> redundant_flag_value == new_flag_value
1593 True
1594
1595Clean up.
1596 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1597
Tim Petersc6cbab02004-08-22 19:43:28 +00001598 """
1599
Tim Peters8485b562004-08-04 18:46:34 +00001600 def option_directives(): r"""
1601Tests of `DocTestRunner`'s option directive mechanism.
1602
Edward Loper74bca7a2004-08-12 02:27:44 +00001603Option directives can be used to turn option flags on or off for a
1604single example. To turn an option on for an example, follow that
1605example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001606
1607 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001608 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001609 ... [0, 1, ..., 9]
1610 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001611 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001612 ... [0, 1, ..., 9]
1613 ... '''
1614 >>> test = doctest.DocTestFinder().find(f)[0]
1615 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001616 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001617 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001618 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001619 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001620 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001621 Expected:
1622 [0, 1, ..., 9]
1623 Got:
1624 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001625 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001626
1627To turn an option off for an example, follow that example with a
1628comment of the form ``# doctest: -OPTION``:
1629
1630 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001631 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001632 ... [0, 1, ..., 9]
1633 ...
1634 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001635 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001636 ... [0, 1, ..., 9]
1637 ... '''
1638 >>> test = doctest.DocTestFinder().find(f)[0]
1639 >>> doctest.DocTestRunner(verbose=False,
1640 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001641 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001642 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001643 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001644 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001645 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001646 Expected:
1647 [0, 1, ..., 9]
1648 Got:
1649 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001650 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001651
1652Option directives affect only the example that they appear with; they
1653do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001654
Edward Loper74bca7a2004-08-12 02:27:44 +00001655 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001656 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001657 ... [0, 1, ..., 9]
1658 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001659 ... >>> print(list(range(10))) # doctest: +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))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001663 ... [0, 1, ..., 9]
1664 ... '''
1665 >>> test = doctest.DocTestFinder().find(f)[0]
1666 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001667 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001668 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001669 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001670 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001671 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001672 Expected:
1673 [0, 1, ..., 9]
1674 Got:
1675 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001676 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001677 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001678 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001679 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001680 Expected:
1681 [0, 1, ..., 9]
1682 Got:
1683 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001684 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001685
Edward Loper74bca7a2004-08-12 02:27:44 +00001686Multiple options may be modified by a single option directive. They
1687may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001688
1689 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001690 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001691 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001692 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001693 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001694 ... [0, 1, ..., 9]
1695 ... '''
1696 >>> test = doctest.DocTestFinder().find(f)[0]
1697 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001698 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001699 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001700 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001701 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001702 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001703 Expected:
1704 [0, 1, ..., 9]
1705 Got:
1706 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001707 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001708
1709 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001710 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001711 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001712 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001713 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1714 ... [0, 1, ..., 9]
1715 ... '''
1716 >>> test = doctest.DocTestFinder().find(f)[0]
1717 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001718 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001719 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001720 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001721 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001722 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001723 Expected:
1724 [0, 1, ..., 9]
1725 Got:
1726 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001727 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001728
1729 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001730 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001731 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001732 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001733 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1734 ... [0, 1, ..., 9]
1735 ... '''
1736 >>> test = doctest.DocTestFinder().find(f)[0]
1737 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001738 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001739 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001740 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001741 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001742 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001743 Expected:
1744 [0, 1, ..., 9]
1745 Got:
1746 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001747 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001748
1749The option directive may be put on the line following the source, as
1750long as a continuation prompt is used:
1751
1752 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001753 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001754 ... ... # doctest: +ELLIPSIS
1755 ... [0, 1, ..., 9]
1756 ... '''
1757 >>> test = doctest.DocTestFinder().find(f)[0]
1758 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001759 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001760
Edward Loper74bca7a2004-08-12 02:27:44 +00001761For examples with multi-line source, the option directive may appear
1762at the end of any line:
1763
1764 >>> def f(x): r'''
1765 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001766 ... ... print(' ', x, end='', sep='')
1767 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001768 ...
1769 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001770 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1771 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001772 ... '''
1773 >>> test = doctest.DocTestFinder().find(f)[0]
1774 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001775 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001776
1777If more than one line of an example with multi-line source has an
1778option directive, then they are combined:
1779
1780 >>> def f(x): r'''
1781 ... Should fail (option directive not on the last line):
1782 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001783 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001784 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001785 ... '''
1786 >>> test = doctest.DocTestFinder().find(f)[0]
1787 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001788 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001789
1790It is an error to have a comment of the form ``# doctest:`` that is
1791*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1792``OPTION`` is an option that has been registered with
1793`register_option`:
1794
1795 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001796 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001797 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1798 Traceback (most recent call last):
1799 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1800
1801 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001802 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001803 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1804 Traceback (most recent call last):
1805 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1806
1807It is an error to use an option directive on a line that contains no
1808source:
1809
1810 >>> s = '>>> # doctest: +ELLIPSIS'
1811 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1812 Traceback (most recent call last):
1813 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 +00001814"""
1815
1816def test_testsource(): r"""
1817Unit tests for `testsource()`.
1818
1819The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001820test with that name in that module, and converts it to a script. The
1821example code is converted to regular Python code. The surrounding
1822words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001823
1824 >>> import test.test_doctest
1825 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001826 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001827 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001828 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001829 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001830 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001831 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001832 #
Edward Lopera5db6002004-08-12 02:41:30 +00001833 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001834 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001835
1836 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001837 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001838 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001839 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001840 ## 1
1841 ## 2
1842 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001843 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001844
1845 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001846 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001847 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001848 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001849 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001850 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001851 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001852 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001853 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001854"""
1855
1856def test_debug(): r"""
1857
1858Create a docstring that we want to debug:
1859
1860 >>> s = '''
1861 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001862 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001863 ... 12
1864 ... '''
1865
1866Create some fake stdin input, to feed to the debugger:
1867
Tim Peters8485b562004-08-04 18:46:34 +00001868 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001869 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001870
1871Run the debugger on the docstring, and then restore sys.stdin.
1872
Edward Loper2de91ba2004-08-27 02:07:46 +00001873 >>> try: doctest.debug_src(s)
1874 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001875 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001876 (Pdb) next
1877 12
Tim Peters8485b562004-08-04 18:46:34 +00001878 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001880 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001881 12
1882 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001883
1884"""
1885
Brett Cannon31f59292011-02-21 19:29:56 +00001886if not hasattr(sys, 'gettrace') or not sys.gettrace():
1887 def test_pdb_set_trace():
1888 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001889
Brett Cannon31f59292011-02-21 19:29:56 +00001890 You can use pdb.set_trace from a doctest. To do so, you must
1891 retrieve the set_trace function from the pdb module at the time
1892 you use it. The doctest module changes sys.stdout so that it can
1893 capture program output. It also temporarily replaces pdb.set_trace
1894 with a version that restores stdout. This is necessary for you to
1895 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001896
Brett Cannon31f59292011-02-21 19:29:56 +00001897 >>> doc = '''
1898 ... >>> x = 42
1899 ... >>> raise Exception('clé')
1900 ... Traceback (most recent call last):
1901 ... Exception: clé
1902 ... >>> import pdb; pdb.set_trace()
1903 ... '''
1904 >>> parser = doctest.DocTestParser()
1905 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1906 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001907
Brett Cannon31f59292011-02-21 19:29:56 +00001908 To demonstrate this, we'll create a fake standard input that
1909 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001910
Brett Cannon31f59292011-02-21 19:29:56 +00001911 >>> real_stdin = sys.stdin
1912 >>> sys.stdin = _FakeInput([
1913 ... 'print(x)', # print data defined by the example
1914 ... 'continue', # stop debugging
1915 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001916
Brett Cannon31f59292011-02-21 19:29:56 +00001917 >>> try: runner.run(test)
1918 ... finally: sys.stdin = real_stdin
1919 --Return--
1920 > <doctest foo-bar@baz[2]>(1)<module>()->None
1921 -> import pdb; pdb.set_trace()
1922 (Pdb) print(x)
1923 42
1924 (Pdb) continue
1925 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001926
Brett Cannon31f59292011-02-21 19:29:56 +00001927 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001928
Brett Cannon31f59292011-02-21 19:29:56 +00001929 >>> def calls_set_trace():
1930 ... y=2
1931 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001932
Brett Cannon31f59292011-02-21 19:29:56 +00001933 >>> doc = '''
1934 ... >>> x=1
1935 ... >>> calls_set_trace()
1936 ... '''
1937 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1938 >>> real_stdin = sys.stdin
1939 >>> sys.stdin = _FakeInput([
1940 ... 'print(y)', # print data defined in the function
1941 ... 'up', # out of function
1942 ... 'print(x)', # print data defined by the example
1943 ... 'continue', # stop debugging
1944 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001945
Brett Cannon31f59292011-02-21 19:29:56 +00001946 >>> try:
1947 ... runner.run(test)
1948 ... finally:
1949 ... sys.stdin = real_stdin
1950 --Return--
Serhiy Storchakae437a102016-04-24 21:41:02 +03001951 > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
Brett Cannon31f59292011-02-21 19:29:56 +00001952 -> import pdb; pdb.set_trace()
1953 (Pdb) print(y)
1954 2
1955 (Pdb) up
1956 > <doctest foo-bar@baz[1]>(1)<module>()
1957 -> calls_set_trace()
1958 (Pdb) print(x)
1959 1
1960 (Pdb) continue
1961 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001962
Brett Cannon31f59292011-02-21 19:29:56 +00001963 During interactive debugging, source code is shown, even for
1964 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001965
Brett Cannon31f59292011-02-21 19:29:56 +00001966 >>> doc = '''
1967 ... >>> def f(x):
1968 ... ... g(x*2)
1969 ... >>> def g(x):
1970 ... ... print(x+3)
1971 ... ... import pdb; pdb.set_trace()
1972 ... >>> f(3)
1973 ... '''
1974 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1975 >>> real_stdin = sys.stdin
1976 >>> sys.stdin = _FakeInput([
1977 ... 'list', # list source from example 2
1978 ... 'next', # return from g()
1979 ... 'list', # list source from example 1
1980 ... 'next', # return from f()
1981 ... 'list', # list source from example 3
1982 ... 'continue', # stop debugging
1983 ... ''])
1984 >>> try: runner.run(test)
1985 ... finally: sys.stdin = real_stdin
1986 ... # doctest: +NORMALIZE_WHITESPACE
1987 --Return--
1988 > <doctest foo-bar@baz[1]>(3)g()->None
1989 -> import pdb; pdb.set_trace()
1990 (Pdb) list
1991 1 def g(x):
1992 2 print(x+3)
1993 3 -> import pdb; pdb.set_trace()
1994 [EOF]
1995 (Pdb) next
1996 --Return--
1997 > <doctest foo-bar@baz[0]>(2)f()->None
1998 -> g(x*2)
1999 (Pdb) list
2000 1 def f(x):
2001 2 -> g(x*2)
2002 [EOF]
2003 (Pdb) next
2004 --Return--
2005 > <doctest foo-bar@baz[2]>(1)<module>()->None
2006 -> f(3)
2007 (Pdb) list
2008 1 -> f(3)
2009 [EOF]
2010 (Pdb) continue
2011 **********************************************************************
2012 File "foo-bar@baz.py", line 7, in foo-bar@baz
2013 Failed example:
2014 f(3)
2015 Expected nothing
2016 Got:
2017 9
2018 TestResults(failed=1, attempted=3)
2019 """
Jim Fulton356fd192004-08-09 11:34:47 +00002020
Brett Cannon31f59292011-02-21 19:29:56 +00002021 def test_pdb_set_trace_nested():
2022 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00002023
Brett Cannon31f59292011-02-21 19:29:56 +00002024 >>> class C(object):
2025 ... def calls_set_trace(self):
2026 ... y = 1
2027 ... import pdb; pdb.set_trace()
2028 ... self.f1()
2029 ... y = 2
2030 ... def f1(self):
2031 ... x = 1
2032 ... self.f2()
2033 ... x = 2
2034 ... def f2(self):
2035 ... z = 1
2036 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002037
Brett Cannon31f59292011-02-21 19:29:56 +00002038 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002039
Brett Cannon31f59292011-02-21 19:29:56 +00002040 >>> doc = '''
2041 ... >>> a = 1
2042 ... >>> calls_set_trace()
2043 ... '''
2044 >>> parser = doctest.DocTestParser()
2045 >>> runner = doctest.DocTestRunner(verbose=False)
2046 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2047 >>> real_stdin = sys.stdin
2048 >>> sys.stdin = _FakeInput([
2049 ... 'print(y)', # print data defined in the function
2050 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2051 ... 'up', 'print(x)',
2052 ... 'up', 'print(y)',
2053 ... 'up', 'print(foo)',
2054 ... 'continue', # stop debugging
2055 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002056
Brett Cannon31f59292011-02-21 19:29:56 +00002057 >>> try:
2058 ... runner.run(test)
2059 ... finally:
2060 ... sys.stdin = real_stdin
2061 ... # doctest: +REPORT_NDIFF
2062 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2063 -> self.f1()
2064 (Pdb) print(y)
2065 1
2066 (Pdb) step
2067 --Call--
2068 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2069 -> def f1(self):
2070 (Pdb) step
2071 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2072 -> x = 1
2073 (Pdb) step
2074 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2075 -> self.f2()
2076 (Pdb) step
2077 --Call--
2078 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2079 -> def f2(self):
2080 (Pdb) step
2081 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2082 -> z = 1
2083 (Pdb) step
2084 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2085 -> z = 2
2086 (Pdb) print(z)
2087 1
2088 (Pdb) up
2089 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2090 -> self.f2()
2091 (Pdb) print(x)
2092 1
2093 (Pdb) up
2094 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2095 -> self.f1()
2096 (Pdb) print(y)
2097 1
2098 (Pdb) up
2099 > <doctest foo-bar@baz[1]>(1)<module>()
2100 -> calls_set_trace()
2101 (Pdb) print(foo)
2102 *** NameError: name 'foo' is not defined
2103 (Pdb) continue
2104 TestResults(failed=0, attempted=2)
2105 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002106
Tim Peters19397e52004-08-06 22:02:59 +00002107def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002108 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002109
2110 We create a Suite by providing a module. A module can be provided
2111 by passing a module object:
2112
2113 >>> import unittest
2114 >>> import test.sample_doctest
2115 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2116 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002117 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002118
2119 We can also supply the module by name:
2120
2121 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2122 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002123 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002124
R David Murray5abd76a2012-09-10 10:15:58 -04002125 The module need not contain any doctest examples:
2126
2127 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2128 >>> suite.run(unittest.TestResult())
2129 <unittest.result.TestResult run=0 errors=0 failures=0>
2130
R David Murray1976d9b2014-04-14 20:28:36 -04002131 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002132
R David Murray1976d9b2014-04-14 20:28:36 -04002133 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002134 >>> suite.run(unittest.TestResult())
2135 <unittest.result.TestResult run=0 errors=0 failures=0>
2136
Tim Peters19397e52004-08-06 22:02:59 +00002137 We can use the current module:
2138
2139 >>> suite = test.sample_doctest.test_suite()
2140 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002141 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002142
R David Murray1976d9b2014-04-14 20:28:36 -04002143 We can also provide a DocTestFinder:
2144
2145 >>> finder = doctest.DocTestFinder()
2146 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2147 ... test_finder=finder)
2148 >>> suite.run(unittest.TestResult())
2149 <unittest.result.TestResult run=9 errors=0 failures=4>
2150
2151 The DocTestFinder need not return any tests:
2152
2153 >>> finder = doctest.DocTestFinder()
2154 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2155 ... test_finder=finder)
2156 >>> suite.run(unittest.TestResult())
2157 <unittest.result.TestResult run=0 errors=0 failures=0>
2158
Tim Peters19397e52004-08-06 22:02:59 +00002159 We can supply global variables. If we pass globs, they will be
2160 used instead of the module globals. Here we'll pass an empty
2161 globals, triggering an extra error:
2162
2163 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2164 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002165 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002166
2167 Alternatively, we can provide extra globals. Here we'll make an
2168 error go away by providing an extra global variable:
2169
2170 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2171 ... extraglobs={'y': 1})
2172 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002173 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002174
2175 You can pass option flags. Here we'll cause an extra error
2176 by disabling the blank-line feature:
2177
2178 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002179 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002180 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002181 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002182
Tim Peters1e277ee2004-08-07 05:37:52 +00002183 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002184
Jim Fultonf54bad42004-08-28 14:57:56 +00002185 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002186 ... import test.test_doctest
2187 ... test.test_doctest.sillySetup = True
2188
Jim Fultonf54bad42004-08-28 14:57:56 +00002189 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002190 ... import test.test_doctest
2191 ... del test.test_doctest.sillySetup
2192
2193 Here, we installed a silly variable that the test expects:
2194
2195 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2196 ... setUp=setUp, tearDown=tearDown)
2197 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002198 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002199
2200 But the tearDown restores sanity:
2201
2202 >>> import test.test_doctest
2203 >>> test.test_doctest.sillySetup
2204 Traceback (most recent call last):
2205 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002206 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002207
Berker Peksag4882cac2015-04-14 09:30:01 +03002208 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002209 we'll use the setUp function to supply the missing variable y:
2210
2211 >>> def setUp(test):
2212 ... test.globs['y'] = 1
2213
2214 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2215 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002216 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002217
2218 Here, we didn't need to use a tearDown function because we
2219 modified the test globals, which are a copy of the
2220 sample_doctest module dictionary. The test globals are
2221 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002222 """
2223
2224def test_DocFileSuite():
2225 """We can test tests found in text files using a DocFileSuite.
2226
2227 We create a suite by providing the names of one or more text
2228 files that include examples:
2229
2230 >>> import unittest
2231 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002232 ... 'test_doctest2.txt',
2233 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002234 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002235 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002236
2237 The test files are looked for in the directory containing the
2238 calling module. A package keyword argument can be provided to
2239 specify a different relative location.
2240
2241 >>> import unittest
2242 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2243 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002244 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002245 ... package='test')
2246 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002247 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002248
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002249 Support for using a package's __loader__.get_data() is also
2250 provided.
2251
2252 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002253 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002254 >>> if not hasattr(test, '__loader__'):
2255 ... test.__loader__ = pkgutil.get_loader(test)
2256 ... added_loader = True
2257 >>> try:
2258 ... suite = doctest.DocFileSuite('test_doctest.txt',
2259 ... 'test_doctest2.txt',
2260 ... 'test_doctest4.txt',
2261 ... package='test')
2262 ... suite.run(unittest.TestResult())
2263 ... finally:
2264 ... if added_loader:
2265 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002266 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002267
Edward Loper0273f5b2004-09-18 20:27:04 +00002268 '/' should be used as a path separator. It will be converted
2269 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002270
2271 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2272 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002273 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002274
Edward Loper0273f5b2004-09-18 20:27:04 +00002275 If DocFileSuite is used from an interactive session, then files
2276 are resolved relative to the directory of sys.argv[0]:
2277
Christian Heimes45f9af32007-11-27 21:50:00 +00002278 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002279 >>> save_argv = sys.argv
2280 >>> sys.argv = [test.test_doctest.__file__]
2281 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002282 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002283 >>> sys.argv = save_argv
2284
Edward Loper052d0cd2004-09-19 17:19:33 +00002285 By setting `module_relative=False`, os-specific paths may be
2286 used (including absolute paths and paths relative to the
2287 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002288
2289 >>> # Get the absolute path of the test package.
2290 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2291 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2292
2293 >>> # Use it to find the absolute path of test_doctest.txt.
2294 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2295
Edward Loper052d0cd2004-09-19 17:19:33 +00002296 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002297 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002298 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002299
Edward Loper052d0cd2004-09-19 17:19:33 +00002300 It is an error to specify `package` when `module_relative=False`:
2301
2302 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2303 ... package='test')
2304 Traceback (most recent call last):
2305 ValueError: Package may only be specified for module-relative paths.
2306
Tim Peters19397e52004-08-06 22:02:59 +00002307 You can specify initial global variables:
2308
2309 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2310 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002311 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002312 ... globs={'favorite_color': 'blue'})
2313 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002314 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002315
2316 In this case, we supplied a missing favorite color. You can
2317 provide doctest options:
2318
2319 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2320 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002321 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002322 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2323 ... globs={'favorite_color': 'blue'})
2324 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002325 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002326
2327 And, you can provide setUp and tearDown functions:
2328
Jim Fultonf54bad42004-08-28 14:57:56 +00002329 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002330 ... import test.test_doctest
2331 ... test.test_doctest.sillySetup = True
2332
Jim Fultonf54bad42004-08-28 14:57:56 +00002333 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002334 ... import test.test_doctest
2335 ... del test.test_doctest.sillySetup
2336
2337 Here, we installed a silly variable that the test expects:
2338
2339 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2340 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002341 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002342 ... setUp=setUp, tearDown=tearDown)
2343 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002344 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002345
2346 But the tearDown restores sanity:
2347
2348 >>> import test.test_doctest
2349 >>> test.test_doctest.sillySetup
2350 Traceback (most recent call last):
2351 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002352 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002353
Berker Peksag4882cac2015-04-14 09:30:01 +03002354 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002355 Here, we'll use a setUp function to set the favorite color in
2356 test_doctest.txt:
2357
2358 >>> def setUp(test):
2359 ... test.globs['favorite_color'] = 'blue'
2360
2361 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2362 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002363 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002364
2365 Here, we didn't need to use a tearDown function because we
2366 modified the test globals. The test globals are
2367 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002368
Fred Drake7c404a42004-12-21 23:46:34 +00002369 Tests in a file run using `DocFileSuite` can also access the
2370 `__file__` global, which is set to the name of the file
2371 containing the tests:
2372
Benjamin Petersonab078e92016-07-13 21:13:29 -07002373 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
Fred Drake7c404a42004-12-21 23:46:34 +00002374 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002375 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002376
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002377 If the tests contain non-ASCII characters, we have to specify which
2378 encoding the file is encoded with. We do so by using the `encoding`
2379 parameter:
2380
2381 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2382 ... 'test_doctest2.txt',
2383 ... 'test_doctest4.txt',
2384 ... encoding='utf-8')
2385 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002386 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002387
Jim Fultonf54bad42004-08-28 14:57:56 +00002388 """
Tim Peters19397e52004-08-06 22:02:59 +00002389
Jim Fulton07a349c2004-08-22 14:10:00 +00002390def test_trailing_space_in_test():
2391 """
Tim Petersa7def722004-08-23 22:13:22 +00002392 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002393
Jim Fulton07a349c2004-08-22 14:10:00 +00002394 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002395 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002396 foo \n
2397 """
Tim Peters19397e52004-08-06 22:02:59 +00002398
Yury Selivanovb532df62014-12-08 15:00:05 -05002399class Wrapper:
2400 def __init__(self, func):
2401 self.func = func
2402 functools.update_wrapper(self, func)
2403
2404 def __call__(self, *args, **kwargs):
2405 self.func(*args, **kwargs)
2406
2407@Wrapper
2408def test_look_in_unwrapped():
2409 """
2410 Docstrings in wrapped functions must be detected as well.
2411
2412 >>> 'one other test'
2413 'one other test'
2414 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002415
2416def test_unittest_reportflags():
2417 """Default unittest reporting flags can be set to control reporting
2418
2419 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2420 only the first failure of each test. First, we'll look at the
2421 output without the flag. The file test_doctest.txt file has two
2422 tests. They both fail if blank lines are disabled:
2423
2424 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2425 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2426 >>> import unittest
2427 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002428 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002429 Traceback ...
2430 Failed example:
2431 favorite_color
2432 ...
2433 Failed example:
2434 if 1:
2435 ...
2436
2437 Note that we see both failures displayed.
2438
2439 >>> old = doctest.set_unittest_reportflags(
2440 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2441
2442 Now, when we run the test:
2443
2444 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002445 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002446 Traceback ...
2447 Failed example:
2448 favorite_color
2449 Exception raised:
2450 ...
2451 NameError: name 'favorite_color' is not defined
2452 <BLANKLINE>
2453 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002454
Jim Fultonf54bad42004-08-28 14:57:56 +00002455 We get only the first failure.
2456
2457 If we give any reporting options when we set up the tests,
2458 however:
2459
2460 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2461 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2462
2463 Then the default eporting options are ignored:
2464
2465 >>> result = suite.run(unittest.TestResult())
Pablo Galindoc5dc60e2019-01-10 14:29:40 +00002466
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302467 *NOTE*: These doctest are intentionally not placed in raw string to depict
2468 the trailing whitespace using `\x20` in the diff below.
2469
Guido van Rossum7131f842007-02-09 20:13:25 +00002470 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002471 Traceback ...
2472 Failed example:
2473 favorite_color
2474 ...
2475 Failed example:
2476 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002477 print('a')
2478 print()
2479 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002480 Differences (ndiff with -expected +actual):
2481 a
2482 - <BLANKLINE>
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302483 +\x20
Jim Fultonf54bad42004-08-28 14:57:56 +00002484 b
2485 <BLANKLINE>
2486 <BLANKLINE>
2487
2488
2489 Test runners can restore the formatting flags after they run:
2490
2491 >>> ignored = doctest.set_unittest_reportflags(old)
2492
2493 """
2494
Edward Loper052d0cd2004-09-19 17:19:33 +00002495def test_testfile(): r"""
2496Tests for the `testfile()` function. This function runs all the
Min ho Kimc4cacc82019-07-31 08:16:13 +10002497doctest examples in a given file. In its simple invocation, it is
Edward Loper052d0cd2004-09-19 17:19:33 +00002498called with the name of a file, which is taken to be relative to the
2499calling module. The return value is (#failures, #tests).
2500
Florent Xicluna59250852010-02-27 14:21:57 +00002501We don't want `-v` in sys.argv for these tests.
2502
2503 >>> save_argv = sys.argv
2504 >>> if '-v' in sys.argv:
2505 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2506
2507
Edward Loper052d0cd2004-09-19 17:19:33 +00002508 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2509 **********************************************************************
2510 File "...", line 6, in test_doctest.txt
2511 Failed example:
2512 favorite_color
2513 Exception raised:
2514 ...
2515 NameError: name 'favorite_color' is not defined
2516 **********************************************************************
2517 1 items had failures:
2518 1 of 2 in test_doctest.txt
2519 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002520 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002521 >>> doctest.master = None # Reset master.
2522
2523(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002524`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002525same name.)
2526
2527Globals may be specified with the `globs` and `extraglobs` parameters:
2528
2529 >>> globs = {'favorite_color': 'blue'}
2530 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002531 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002532 >>> doctest.master = None # Reset master.
2533
2534 >>> extraglobs = {'favorite_color': 'red'}
2535 >>> doctest.testfile('test_doctest.txt', globs=globs,
2536 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2537 **********************************************************************
2538 File "...", line 6, in test_doctest.txt
2539 Failed example:
2540 favorite_color
2541 Expected:
2542 'blue'
2543 Got:
2544 'red'
2545 **********************************************************************
2546 1 items had failures:
2547 1 of 2 in test_doctest.txt
2548 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002549 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002550 >>> doctest.master = None # Reset master.
2551
2552The file may be made relative to a given module or package, using the
2553optional `module_relative` parameter:
2554
2555 >>> doctest.testfile('test_doctest.txt', globs=globs,
2556 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002557 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002558 >>> doctest.master = None # Reset master.
2559
Ezio Melotti13925002011-03-16 11:05:33 +02002560Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002561
2562 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2563 Trying:
2564 favorite_color
2565 Expecting:
2566 'blue'
2567 ok
2568 Trying:
2569 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002570 print('a')
2571 print()
2572 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002573 Expecting:
2574 a
2575 <BLANKLINE>
2576 b
2577 ok
2578 1 items passed all tests:
2579 2 tests in test_doctest.txt
2580 2 tests in 1 items.
2581 2 passed and 0 failed.
2582 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002583 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002584 >>> doctest.master = None # Reset master.
2585
2586The name of the test may be specified with the optional `name`
2587parameter:
2588
2589 >>> doctest.testfile('test_doctest.txt', name='newname')
2590 ... # doctest: +ELLIPSIS
2591 **********************************************************************
2592 File "...", line 6, in newname
2593 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002594 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002595 >>> doctest.master = None # Reset master.
2596
Ezio Melotti13925002011-03-16 11:05:33 +02002597The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002598parameter:
2599
2600 >>> doctest.testfile('test_doctest.txt', report=False)
2601 ... # doctest: +ELLIPSIS
2602 **********************************************************************
2603 File "...", line 6, in test_doctest.txt
2604 Failed example:
2605 favorite_color
2606 Exception raised:
2607 ...
2608 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002609 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002610 >>> doctest.master = None # Reset master.
2611
2612The optional keyword argument `raise_on_error` can be used to raise an
2613exception on the first error (which may be useful for postmortem
2614debugging):
2615
2616 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2617 ... # doctest: +ELLIPSIS
2618 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002619 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002620 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002621
2622If the tests contain non-ASCII characters, the tests might fail, since
2623it's unknown which encoding is used. The encoding can be specified
2624using the optional keyword argument `encoding`:
2625
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002626 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002627 **********************************************************************
2628 File "...", line 7, in test_doctest4.txt
2629 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002630 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002631 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002632 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002633 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002634 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002635 **********************************************************************
2636 ...
2637 **********************************************************************
2638 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002639 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002640 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002641 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002642 >>> doctest.master = None # Reset master.
2643
2644 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002645 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002646 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002647
2648Test the verbose output:
2649
2650 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2651 Trying:
2652 'föö'
2653 Expecting:
2654 'f\xf6\xf6'
2655 ok
2656 Trying:
2657 'bÄ…r'
2658 Expecting:
2659 'b\u0105r'
2660 ok
2661 1 items passed all tests:
2662 2 tests in test_doctest4.txt
2663 2 tests in 1 items.
2664 2 passed and 0 failed.
2665 Test passed.
2666 TestResults(failed=0, attempted=2)
2667 >>> doctest.master = None # Reset master.
2668 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002669"""
2670
Peter Donise0b81012020-03-26 11:53:16 -04002671class TestImporter(importlib.abc.MetaPathFinder, importlib.abc.ResourceLoader):
2672
2673 def find_spec(self, fullname, path, target=None):
2674 return importlib.util.spec_from_file_location(fullname, path, loader=self)
2675
2676 def get_data(self, path):
2677 with open(path, mode='rb') as f:
2678 return f.read()
2679
2680class TestHook:
2681
2682 def __init__(self, pathdir):
2683 self.sys_path = sys.path[:]
2684 self.meta_path = sys.meta_path[:]
2685 self.path_hooks = sys.path_hooks[:]
2686 sys.path.append(pathdir)
2687 sys.path_importer_cache.clear()
2688 self.modules_before = sys.modules.copy()
2689 self.importer = TestImporter()
2690 sys.meta_path.append(self.importer)
2691
2692 def remove(self):
2693 sys.path[:] = self.sys_path
2694 sys.meta_path[:] = self.meta_path
2695 sys.path_hooks[:] = self.path_hooks
2696 sys.path_importer_cache.clear()
2697 sys.modules.clear()
2698 sys.modules.update(self.modules_before)
2699
2700
2701@contextlib.contextmanager
2702def test_hook(pathdir):
2703 hook = TestHook(pathdir)
2704 try:
2705 yield hook
2706 finally:
2707 hook.remove()
2708
2709
R David Murrayb48cb292014-10-02 22:42:42 -04002710def test_lineendings(): r"""
Peter Donise0b81012020-03-26 11:53:16 -04002711*nix systems use \n line endings, while Windows systems use \r\n, and
2712old Mac systems used \r, which Python still recognizes as a line ending. Python
R David Murrayb48cb292014-10-02 22:42:42 -04002713handles this using universal newline mode for reading files. Let's make
2714sure doctest does so (issue 8473) by creating temporary test files using each
Peter Donise0b81012020-03-26 11:53:16 -04002715of the three line disciplines. At least one will not match either the universal
2716newline \n or os.linesep for the platform the test is run on.
R David Murrayb48cb292014-10-02 22:42:42 -04002717
2718Windows line endings first:
2719
2720 >>> import tempfile, os
2721 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002722 >>> with open(fn, 'wb') as f:
2723 ... 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 -04002724 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002725 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002726 TestResults(failed=0, attempted=1)
2727 >>> os.remove(fn)
2728
2729And now *nix line endings:
2730
2731 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002732 >>> with open(fn, 'wb') as f:
2733 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002734 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002735 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002736 TestResults(failed=0, attempted=1)
2737 >>> os.remove(fn)
2738
Peter Donise0b81012020-03-26 11:53:16 -04002739And finally old Mac line endings:
2740
2741 >>> fn = tempfile.mktemp()
2742 >>> with open(fn, 'wb') as f:
2743 ... f.write(b'Test:\r\r >>> x = 1 + 1\r\rDone.\r')
2744 30
2745 >>> doctest.testfile(fn, module_relative=False, verbose=False)
2746 TestResults(failed=0, attempted=1)
2747 >>> os.remove(fn)
2748
2749Now we test with a package loader that has a get_data method, since that
2750bypasses the standard universal newline handling so doctest has to do the
2751newline conversion itself; let's make sure it does so correctly (issue 1812).
2752We'll write a file inside the package that has all three kinds of line endings
2753in it, and use a package hook to install a custom loader; on any platform,
2754at least one of the line endings will raise a ValueError for inconsistent
2755whitespace if doctest does not correctly do the newline conversion.
2756
2757 >>> dn = tempfile.mkdtemp()
2758 >>> pkg = os.path.join(dn, "doctest_testpkg")
2759 >>> os.mkdir(pkg)
2760 >>> support.create_empty_file(os.path.join(pkg, "__init__.py"))
2761 >>> fn = os.path.join(pkg, "doctest_testfile.txt")
2762 >>> with open(fn, 'wb') as f:
2763 ... f.write(
2764 ... b'Test:\r\n\r\n'
2765 ... b' >>> x = 1 + 1\r\n\r\n'
2766 ... b'Done.\r\n'
2767 ... b'Test:\n\n'
2768 ... b' >>> x = 1 + 1\n\n'
2769 ... b'Done.\n'
2770 ... b'Test:\r\r'
2771 ... b' >>> x = 1 + 1\r\r'
2772 ... b'Done.\r'
2773 ... )
2774 95
2775 >>> with test_hook(dn):
2776 ... doctest.testfile("doctest_testfile.txt", package="doctest_testpkg", verbose=False)
2777 TestResults(failed=0, attempted=3)
2778 >>> shutil.rmtree(dn)
2779
R David Murrayb48cb292014-10-02 22:42:42 -04002780"""
2781
R. David Murray58641de2009-06-12 15:33:19 +00002782def test_testmod(): r"""
2783Tests for the testmod function. More might be useful, but for now we're just
2784testing the case raised by Issue 6195, where trying to doctest a C module would
2785fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2786out of the binary module.
2787
2788 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002789 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002790 TestResults(failed=0, attempted=0)
2791"""
2792
Victor Stinner9d396392010-10-16 21:54:59 +00002793try:
2794 os.fsencode("foo-bär@baz.py")
2795except UnicodeEncodeError:
2796 # Skip the test: the filesystem encoding is unable to encode the filename
2797 pass
2798else:
2799 def test_unicode(): """
2800Check doctest with a non-ascii filename:
2801
2802 >>> doc = '''
2803 ... >>> raise Exception('clé')
2804 ... '''
2805 ...
2806 >>> parser = doctest.DocTestParser()
2807 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2808 >>> test
2809 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2810 >>> runner = doctest.DocTestRunner(verbose=False)
2811 >>> runner.run(test) # doctest: +ELLIPSIS
2812 **********************************************************************
2813 File "foo-bär@baz.py", line 2, in foo-bär@baz
2814 Failed example:
2815 raise Exception('clé')
2816 Exception raised:
2817 Traceback (most recent call last):
2818 File ...
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03002819 exec(compile(example.source, filename, "single",
Victor Stinner9d396392010-10-16 21:54:59 +00002820 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2821 raise Exception('clé')
2822 Exception: clé
2823 TestResults(failed=1, attempted=1)
2824 """
2825
R David Murray5707d502013-06-23 14:24:13 -04002826def test_CLI(): r"""
2827The doctest module can be used to run doctests against an arbitrary file.
2828These tests test this CLI functionality.
2829
2830We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002831to a temp dir to run the command against. Due to a current limitation in
2832script_helpers, though, we need a little utility function to turn the returned
2833output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002834
R David Murray4af68982013-06-25 08:11:22 -04002835 >>> def normalize(s):
2836 ... return '\n'.join(s.decode().splitlines())
2837
R David Murray4af68982013-06-25 08:11:22 -04002838With those preliminaries out of the way, we'll start with a file with two
2839simple tests and no errors. We'll run both the unadorned doctest command, and
2840the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002841
Berker Peksagce643912015-05-06 06:33:17 +03002842 >>> from test.support import script_helper, temp_dir
2843 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002844 ... fn = os.path.join(tmpdir, 'myfile.doc')
2845 ... with open(fn, 'w') as f:
2846 ... _ = f.write('This is a very simple test file.\n')
2847 ... _ = f.write(' >>> 1 + 1\n')
2848 ... _ = f.write(' 2\n')
2849 ... _ = f.write(' >>> "a"\n')
2850 ... _ = f.write(" 'a'\n")
2851 ... _ = f.write('\n')
2852 ... _ = f.write('And that is it.\n')
2853 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002854 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002855 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002856 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002857
2858With no arguments and passing tests, we should get no output:
2859
2860 >>> rc1, out1, err1
2861 (0, b'', b'')
2862
2863With the verbose flag, we should see the test output, but no error output:
2864
2865 >>> rc2, err2
2866 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002867 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002868 Trying:
2869 1 + 1
2870 Expecting:
2871 2
2872 ok
2873 Trying:
2874 "a"
2875 Expecting:
2876 'a'
2877 ok
2878 1 items passed all tests:
2879 2 tests in myfile.doc
2880 2 tests in 1 items.
2881 2 passed and 0 failed.
2882 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002883
2884Now we'll write a couple files, one with three tests, the other a python module
2885with two tests, both of the files having "errors" in the tests that can be made
2886non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2887the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002888allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002889ability to process more than one file on the command line and, since the second
2890file ends in '.py', its handling of python module files (as opposed to straight
2891text files).
2892
Berker Peksagce643912015-05-06 06:33:17 +03002893 >>> from test.support import script_helper, temp_dir
2894 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002895 ... fn = os.path.join(tmpdir, 'myfile.doc')
2896 ... with open(fn, 'w') as f:
2897 ... _ = f.write('This is another simple test file.\n')
2898 ... _ = f.write(' >>> 1 + 1\n')
2899 ... _ = f.write(' 2\n')
2900 ... _ = f.write(' >>> "abcdef"\n')
2901 ... _ = f.write(" 'a...f'\n")
2902 ... _ = f.write(' >>> "ajkml"\n')
2903 ... _ = f.write(" 'a...l'\n")
2904 ... _ = f.write('\n')
2905 ... _ = f.write('And that is it.\n')
2906 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2907 ... with open(fn2, 'w') as f:
2908 ... _ = f.write('def test_func():\n')
2909 ... _ = f.write(' \"\"\"\n')
2910 ... _ = f.write(' This is simple python test function.\n')
2911 ... _ = f.write(' >>> 1 + 1\n')
2912 ... _ = f.write(' 2\n')
2913 ... _ = f.write(' >>> "abc def"\n')
2914 ... _ = f.write(" 'abc def'\n")
2915 ... _ = f.write("\n")
2916 ... _ = f.write(' \"\"\"\n')
R David Murray5707d502013-06-23 14:24:13 -04002917 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002918 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002919 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002920 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002921 ... rc3, out3, err3 = script_helper.assert_python_ok(
2922 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002923 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002924 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002925 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002926 ... rc5, out5, err5 = script_helper.assert_python_ok(
2927 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002928 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002929
2930Our first test run will show the errors from the first file (doctest stops if a
2931file has errors). Note that doctest test-run error output appears on stdout,
2932not stderr:
2933
2934 >>> rc1, err1
2935 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002936 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002937 **********************************************************************
2938 File "...myfile.doc", line 4, in myfile.doc
2939 Failed example:
2940 "abcdef"
2941 Expected:
2942 'a...f'
2943 Got:
2944 'abcdef'
2945 **********************************************************************
2946 File "...myfile.doc", line 6, in myfile.doc
2947 Failed example:
2948 "ajkml"
2949 Expected:
2950 'a...l'
2951 Got:
2952 'ajkml'
2953 **********************************************************************
2954 1 items had failures:
2955 2 of 3 in myfile.doc
2956 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002957
2958With -o ELLIPSIS specified, the second run, against just the first file, should
2959produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2960should the third, which ran against both files:
2961
2962 >>> rc2, out2, err2
2963 (0, b'', b'')
2964 >>> rc3, out3, err3
2965 (0, b'', b'')
2966
2967The fourth run uses FAIL_FAST, so we should see only one error:
2968
2969 >>> rc4, err4
2970 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002971 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002972 **********************************************************************
2973 File "...myfile.doc", line 4, in myfile.doc
2974 Failed example:
2975 "abcdef"
2976 Expected:
2977 'a...f'
2978 Got:
2979 'abcdef'
2980 **********************************************************************
2981 1 items had failures:
2982 1 of 2 in myfile.doc
2983 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002984
2985The fifth test uses verbose with the two options, so we should get verbose
2986success output for the tests in both files:
2987
2988 >>> rc5, err5
2989 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002990 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002991 Trying:
2992 1 + 1
2993 Expecting:
2994 2
2995 ok
2996 Trying:
2997 "abcdef"
2998 Expecting:
2999 'a...f'
3000 ok
3001 Trying:
3002 "ajkml"
3003 Expecting:
3004 'a...l'
3005 ok
3006 1 items passed all tests:
3007 3 tests in myfile.doc
3008 3 tests in 1 items.
3009 3 passed and 0 failed.
3010 Test passed.
3011 Trying:
3012 1 + 1
3013 Expecting:
3014 2
3015 ok
3016 Trying:
3017 "abc def"
3018 Expecting:
3019 'abc def'
3020 ok
3021 1 items had no tests:
3022 myfile2
3023 1 items passed all tests:
3024 2 tests in myfile2.test_func
3025 2 tests in 2 items.
3026 2 passed and 0 failed.
3027 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04003028
3029We should also check some typical error cases.
3030
3031Invalid file name:
3032
3033 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03003034 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04003035 >>> rc, out
3036 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04003037 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003038 Traceback (most recent call last):
3039 ...
3040 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
3041
3042Invalid doctest option:
3043
3044 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03003045 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04003046 >>> rc, out
3047 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04003048 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003049 usage...invalid...nosuchoption...
3050
3051"""
3052
Sanyam Khuranacbb16452019-01-09 19:08:38 +05303053def test_no_trailing_whitespace_stripping():
3054 r"""
3055 The fancy reports had a bug for a long time where any trailing whitespace on
3056 the reported diff lines was stripped, making it impossible to see the
3057 differences in line reported as different that differed only in the amount of
3058 trailing whitespace. The whitespace still isn't particularly visible unless
3059 you use NDIFF, but at least it is now there to be found.
3060
3061 *NOTE*: This snippet was intentionally put inside a raw string to get rid of
3062 leading whitespace error in executing the example below
3063
3064 >>> def f(x):
3065 ... r'''
3066 ... >>> print('\n'.join(['a ', 'b']))
3067 ... a
3068 ... b
3069 ... '''
3070 """
3071 """
3072 *NOTE*: These doctest are not placed in raw string to depict the trailing whitespace
3073 using `\x20`
3074
3075 >>> test = doctest.DocTestFinder().find(f)[0]
3076 >>> flags = doctest.REPORT_NDIFF
3077 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
3078 ... # doctest: +ELLIPSIS
3079 **********************************************************************
3080 File ..., line 3, in f
3081 Failed example:
3082 print('\n'.join(['a ', 'b']))
3083 Differences (ndiff with -expected +actual):
3084 - a
3085 + a
3086 b
3087 TestResults(failed=1, attempted=1)
3088
3089 *NOTE*: `\x20` is for checking the trailing whitespace on the +a line above.
3090 We cannot use actual spaces there, as a commit hook prevents from committing
3091 patches that contain trailing whitespace. More info on Issue 24746.
3092 """
3093
Tim Peters8485b562004-08-04 18:46:34 +00003094######################################################################
3095## Main
3096######################################################################
3097
3098def test_main():
3099 # Check the doctest cases in doctest itself:
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02003100 ret = support.run_doctest(doctest, verbosity=True)
Victor Stinner931602a2016-03-25 12:48:17 +01003101
Tim Peters8485b562004-08-04 18:46:34 +00003102 # Check the doctest cases defined here:
3103 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003104 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00003105
Jason R. Coombsb9650a02018-03-05 18:29:08 -05003106 # Run unittests
3107 support.run_unittest(__name__)
3108
3109
Tim Peters8485b562004-08-04 18:46:34 +00003110def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00003111 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01003112 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00003113 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00003114 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00003115 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003116 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00003117 r.write_results(show_missing=True, summary=True,
3118 coverdir=coverdir)
3119
3120if __name__ == '__main__':
3121 if '-c' in sys.argv:
3122 test_coverage('/tmp/doctest.cover')
3123 else:
3124 test_main()