blob: 71426277d2d937520a01c4b957ea68f75cdd9c82 [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)
Guido van Rossum48b069a2020-04-07 09:50:06 -0700668 >>> 810 < len(tests) < 830 # 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. Smith0c2f9302019-05-29 11:46:58 -0700672 12
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
688
689Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
690'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
691and 'int' is a type.
Tim Peters8485b562004-08-04 18:46:34 +0000692"""
693
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500694
695class TestDocTestFinder(unittest.TestCase):
696
697 def test_empty_namespace_package(self):
698 pkg_name = 'doctest_empty_pkg'
Nick Coghland5d9e022018-03-25 23:03:10 +1000699 with tempfile.TemporaryDirectory() as parent_dir:
700 pkg_dir = os.path.join(parent_dir, pkg_name)
701 os.mkdir(pkg_dir)
702 sys.path.append(parent_dir)
703 try:
704 mod = importlib.import_module(pkg_name)
705 finally:
706 support.forget(pkg_name)
707 sys.path.pop()
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500708
Xtreak8289e272019-12-13 23:36:53 +0530709 include_empty_finder = doctest.DocTestFinder(exclude_empty=False)
710 exclude_empty_finder = doctest.DocTestFinder(exclude_empty=True)
711
712 self.assertEqual(len(include_empty_finder.find(mod)), 1)
713 self.assertEqual(len(exclude_empty_finder.find(mod)), 0)
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500714
Edward Loper00f8da72004-08-26 18:05:07 +0000715def test_DocTestParser(): r"""
716Unit tests for the `DocTestParser` class.
717
718DocTestParser is used to parse docstrings containing doctest examples.
719
720The `parse` method divides a docstring into examples and intervening
721text:
722
723 >>> s = '''
724 ... >>> x, y = 2, 3 # no output expected
725 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000726 ... ... print(x)
727 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000728 ... 2
729 ... 3
730 ...
731 ... Some text.
732 ... >>> x+y
733 ... 5
734 ... '''
735 >>> parser = doctest.DocTestParser()
736 >>> for piece in parser.parse(s):
737 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000738 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000739 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000740 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000741 Text: '\n'
742 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
743 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000744 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000745 Text: '\nSome text.\n'
746 Example: ('x+y\n', '5\n', 9)
747 Text: ''
748
749The `get_examples` method returns just the examples:
750
751 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000752 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000753 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000754 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000755 ('x+y\n', '5\n', 9)
756
757The `get_doctest` method creates a Test from the examples, along with the
758given arguments:
759
760 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
761 >>> (test.name, test.filename, test.lineno)
762 ('name', 'filename', 5)
763 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000764 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000765 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000766 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000767 ('x+y\n', '5\n', 9)
768"""
769
Tim Peters8485b562004-08-04 18:46:34 +0000770class test_DocTestRunner:
771 def basics(): r"""
772Unit tests for the `DocTestRunner` class.
773
774DocTestRunner is used to run DocTest test cases, and to accumulate
775statistics. Here's a simple DocTest case we can use:
776
777 >>> def f(x):
778 ... '''
779 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000780 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000781 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000782 ... >>> x//2
783 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000784 ... '''
785 >>> test = doctest.DocTestFinder().find(f)[0]
786
787The main DocTestRunner interface is the `run` method, which runs a
788given DocTest case in a given namespace (globs). It returns a tuple
789`(f,t)`, where `f` is the number of failed tests and `t` is the number
790of tried tests.
791
792 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000793 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000794
795If any example produces incorrect output, then the test runner reports
796the failure and proceeds to the next example:
797
798 >>> def f(x):
799 ... '''
800 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000801 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000802 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000803 ... >>> x//2
804 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000805 ... '''
806 >>> test = doctest.DocTestFinder().find(f)[0]
807 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000808 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000809 Trying:
810 x = 12
811 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000812 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000813 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000814 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000815 Expecting:
816 14
Tim Peters8485b562004-08-04 18:46:34 +0000817 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000818 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000819 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000820 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000821 Expected:
822 14
823 Got:
824 12
Edward Loperaacf0832004-08-26 01:19:50 +0000825 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000827 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000828 6
Tim Peters8485b562004-08-04 18:46:34 +0000829 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000830 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000831"""
832 def verbose_flag(): r"""
833The `verbose` flag makes the test runner generate more detailed
834output:
835
836 >>> def f(x):
837 ... '''
838 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000839 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000840 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000841 ... >>> x//2
842 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000843 ... '''
844 >>> test = doctest.DocTestFinder().find(f)[0]
845
846 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000847 Trying:
848 x = 12
849 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000850 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000851 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000852 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000853 Expecting:
854 12
Tim Peters8485b562004-08-04 18:46:34 +0000855 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000856 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000857 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000858 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000859 6
Tim Peters8485b562004-08-04 18:46:34 +0000860 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000861 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000862
863If the `verbose` flag is unspecified, then the output will be verbose
864iff `-v` appears in sys.argv:
865
866 >>> # Save the real sys.argv list.
867 >>> old_argv = sys.argv
868
869 >>> # If -v does not appear in sys.argv, then output isn't verbose.
870 >>> sys.argv = ['test']
871 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000872 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000873
874 >>> # If -v does appear in sys.argv, then output is verbose.
875 >>> sys.argv = ['test', '-v']
876 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000877 Trying:
878 x = 12
879 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000880 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000881 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000882 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000883 Expecting:
884 12
Tim Peters8485b562004-08-04 18:46:34 +0000885 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000886 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000887 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000888 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000889 6
Tim Peters8485b562004-08-04 18:46:34 +0000890 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000891 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000892
893 >>> # Restore sys.argv
894 >>> sys.argv = old_argv
895
896In the remaining examples, the test runner's verbosity will be
897explicitly set, to ensure that the test behavior is consistent.
898 """
899 def exceptions(): r"""
900Tests of `DocTestRunner`'s exception handling.
901
902An expected exception is specified with a traceback message. The
903lines between the first line and the type/value may be omitted or
904replaced with any other string:
905
906 >>> def f(x):
907 ... '''
908 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000909 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000910 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000911 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000912 ... '''
913 >>> test = doctest.DocTestFinder().find(f)[0]
914 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000915 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000916
Edward Loper19b19582004-08-25 23:07:03 +0000917An example may not generate output before it raises an exception; if
918it does, then the traceback message will not be recognized as
919signaling an expected exception, so the example will be reported as an
920unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000921
922 >>> def f(x):
923 ... '''
924 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000925 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000926 ... pre-exception output
927 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000928 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000929 ... '''
930 >>> test = doctest.DocTestFinder().find(f)[0]
931 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000932 ... # doctest: +ELLIPSIS
933 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000934 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000935 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000936 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000937 Exception raised:
938 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000939 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000940 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000941
942Exception messages may contain newlines:
943
944 >>> def f(x):
945 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000946 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000947 ... Traceback (most recent call last):
948 ... ValueError: multi
949 ... line
950 ... message
951 ... '''
952 >>> test = doctest.DocTestFinder().find(f)[0]
953 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000954 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000955
956If an exception is expected, but an exception with the wrong type or
957message is raised, then it is reported as a failure:
958
959 >>> def f(x):
960 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000961 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000962 ... Traceback (most recent call last):
963 ... ValueError: wrong message
964 ... '''
965 >>> test = doctest.DocTestFinder().find(f)[0]
966 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000967 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000968 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000969 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000970 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000971 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000972 Expected:
973 Traceback (most recent call last):
974 ValueError: wrong message
975 Got:
976 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000977 ...
Tim Peters8485b562004-08-04 18:46:34 +0000978 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000979 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000980
Tim Peters1fbf9c52004-09-04 17:21:02 +0000981However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
982detail:
983
984 >>> def f(x):
985 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000986 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000987 ... Traceback (most recent call last):
988 ... ValueError: wrong message
989 ... '''
990 >>> test = doctest.DocTestFinder().find(f)[0]
991 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000992 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000993
Nick Coghlan5e76e942010-06-12 13:42:46 +0000994IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
995between Python versions. For example, in Python 2.x, the module path of
996the exception is not in the output, but this will fail under Python 3:
997
998 >>> def f(x):
999 ... r'''
1000 ... >>> from http.client import HTTPException
1001 ... >>> raise HTTPException('message')
1002 ... Traceback (most recent call last):
1003 ... HTTPException: message
1004 ... '''
1005 >>> test = doctest.DocTestFinder().find(f)[0]
1006 >>> doctest.DocTestRunner(verbose=False).run(test)
1007 ... # doctest: +ELLIPSIS
1008 **********************************************************************
1009 File ..., line 4, in f
1010 Failed example:
1011 raise HTTPException('message')
1012 Expected:
1013 Traceback (most recent call last):
1014 HTTPException: message
1015 Got:
1016 Traceback (most recent call last):
1017 ...
1018 http.client.HTTPException: message
1019 TestResults(failed=1, attempted=2)
1020
1021But in Python 3 the module path is included, and therefore a test must look
1022like the following test to succeed in Python 3. But that test will fail under
1023Python 2.
1024
1025 >>> def f(x):
1026 ... r'''
1027 ... >>> from http.client import HTTPException
1028 ... >>> raise HTTPException('message')
1029 ... Traceback (most recent call last):
1030 ... http.client.HTTPException: message
1031 ... '''
1032 >>> test = doctest.DocTestFinder().find(f)[0]
1033 >>> doctest.DocTestRunner(verbose=False).run(test)
1034 TestResults(failed=0, attempted=2)
1035
1036However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1037(or its unexpected absence) will be ignored:
1038
1039 >>> def f(x):
1040 ... r'''
1041 ... >>> from http.client import HTTPException
1042 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1043 ... Traceback (most recent call last):
1044 ... HTTPException: message
1045 ... '''
1046 >>> test = doctest.DocTestFinder().find(f)[0]
1047 >>> doctest.DocTestRunner(verbose=False).run(test)
1048 TestResults(failed=0, attempted=2)
1049
1050The module path will be completely ignored, so two different module paths will
1051still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1052be used when exceptions have changed module.
1053
1054 >>> def f(x):
1055 ... r'''
1056 ... >>> from http.client import HTTPException
1057 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1058 ... Traceback (most recent call last):
1059 ... foo.bar.HTTPException: message
1060 ... '''
1061 >>> test = doctest.DocTestFinder().find(f)[0]
1062 >>> doctest.DocTestRunner(verbose=False).run(test)
1063 TestResults(failed=0, attempted=2)
1064
Tim Peters1fbf9c52004-09-04 17:21:02 +00001065But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1066
1067 >>> def f(x):
1068 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001069 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001070 ... Traceback (most recent call last):
1071 ... TypeError: wrong type
1072 ... '''
1073 >>> test = doctest.DocTestFinder().find(f)[0]
1074 >>> doctest.DocTestRunner(verbose=False).run(test)
1075 ... # doctest: +ELLIPSIS
1076 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001077 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001078 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001079 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001080 Expected:
1081 Traceback (most recent call last):
1082 TypeError: wrong type
1083 Got:
1084 Traceback (most recent call last):
1085 ...
1086 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001087 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001088
Tim Petersf9a07f22013-12-03 21:02:05 -06001089If the exception does not have a message, you can still use
1090IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1091
1092 >>> def f(x):
1093 ... r'''
1094 ... >>> from http.client import HTTPException
1095 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1096 ... Traceback (most recent call last):
1097 ... foo.bar.HTTPException
1098 ... '''
1099 >>> test = doctest.DocTestFinder().find(f)[0]
1100 >>> doctest.DocTestRunner(verbose=False).run(test)
1101 TestResults(failed=0, attempted=2)
1102
1103Note that a trailing colon doesn't matter either:
1104
1105 >>> def f(x):
1106 ... r'''
1107 ... >>> from http.client import HTTPException
1108 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1109 ... Traceback (most recent call last):
1110 ... foo.bar.HTTPException:
1111 ... '''
1112 >>> test = doctest.DocTestFinder().find(f)[0]
1113 >>> doctest.DocTestRunner(verbose=False).run(test)
1114 TestResults(failed=0, attempted=2)
1115
Tim Peters8485b562004-08-04 18:46:34 +00001116If an exception is raised but not expected, then it is reported as an
1117unexpected exception:
1118
Tim Peters8485b562004-08-04 18:46:34 +00001119 >>> def f(x):
1120 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001121 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001122 ... 0
1123 ... '''
1124 >>> test = doctest.DocTestFinder().find(f)[0]
1125 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001126 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001127 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001128 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001129 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001130 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001131 Exception raised:
1132 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001133 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001134 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001135 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001136"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001137 def displayhook(): r"""
1138Test that changing sys.displayhook doesn't matter for doctest.
1139
1140 >>> import sys
1141 >>> orig_displayhook = sys.displayhook
1142 >>> def my_displayhook(x):
1143 ... print('hi!')
1144 >>> sys.displayhook = my_displayhook
1145 >>> def f():
1146 ... '''
1147 ... >>> 3
1148 ... 3
1149 ... '''
1150 >>> test = doctest.DocTestFinder().find(f)[0]
1151 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1152 >>> post_displayhook = sys.displayhook
1153
1154 We need to restore sys.displayhook now, so that we'll be able to test
1155 results.
1156
1157 >>> sys.displayhook = orig_displayhook
1158
1159 Ok, now we can check that everything is ok.
1160
1161 >>> r
1162 TestResults(failed=0, attempted=1)
1163 >>> post_displayhook is my_displayhook
1164 True
1165"""
Tim Peters8485b562004-08-04 18:46:34 +00001166 def optionflags(): r"""
1167Tests of `DocTestRunner`'s option flag handling.
1168
1169Several option flags can be used to customize the behavior of the test
1170runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001171to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001172together).
1173
1174The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1175and 1/0:
1176
1177 >>> def f(x):
1178 ... '>>> True\n1\n'
1179
1180 >>> # Without the flag:
1181 >>> test = doctest.DocTestFinder().find(f)[0]
1182 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001183 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001184
1185 >>> # With the flag:
1186 >>> test = doctest.DocTestFinder().find(f)[0]
1187 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1188 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001189 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001190 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001191 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001192 Failed example:
1193 True
1194 Expected:
1195 1
1196 Got:
1197 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001198 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001199
1200The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1201and the '<BLANKLINE>' marker:
1202
1203 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001204 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001205
1206 >>> # Without the flag:
1207 >>> test = doctest.DocTestFinder().find(f)[0]
1208 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001209 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001210
1211 >>> # With the flag:
1212 >>> test = doctest.DocTestFinder().find(f)[0]
1213 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1214 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001215 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001216 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001217 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001218 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001219 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001220 Expected:
1221 a
1222 <BLANKLINE>
1223 b
1224 Got:
1225 a
1226 <BLANKLINE>
1227 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001228 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001229
1230The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1231treated as equal:
1232
1233 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001234 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001235
1236 >>> # Without the flag:
1237 >>> test = doctest.DocTestFinder().find(f)[0]
1238 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001239 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001240 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001241 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001242 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001243 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001244 Expected:
1245 1 2
1246 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001247 Got:
1248 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001249 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001250
1251 >>> # With the flag:
1252 >>> test = doctest.DocTestFinder().find(f)[0]
1253 >>> flags = doctest.NORMALIZE_WHITESPACE
1254 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001255 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001256
Tim Peters026f8dc2004-08-19 16:38:58 +00001257 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001258 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001259 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1260 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1261
Tim Peters8485b562004-08-04 18:46:34 +00001262The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1263output to match any substring in the actual output:
1264
1265 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001266 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001267
1268 >>> # Without the flag:
1269 >>> test = doctest.DocTestFinder().find(f)[0]
1270 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001271 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001272 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001273 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001274 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001275 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001276 Expected:
1277 [0, 1, 2, ..., 14]
1278 Got:
1279 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001280 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001281
1282 >>> # With the flag:
1283 >>> test = doctest.DocTestFinder().find(f)[0]
1284 >>> flags = doctest.ELLIPSIS
1285 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001286 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001287
Tim Peterse594bee2004-08-22 01:47:51 +00001288 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001289
Guido van Rossume0192e52007-02-09 23:39:59 +00001290 >>> if 1:
1291 ... for i in range(100):
1292 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1293 ... print('!')
1294 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001295
Tim Peters026f8dc2004-08-19 16:38:58 +00001296 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001297
Guido van Rossume0192e52007-02-09 23:39:59 +00001298 >>> if 1: #doctest: +ELLIPSIS
1299 ... for i in range(20):
1300 ... print(i, end=' ')
1301 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001302 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001303
Tim Peters026f8dc2004-08-19 16:38:58 +00001304 Examples from the docs:
1305
Guido van Rossum805365e2007-05-07 22:24:25 +00001306 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001307 [0, 1, ..., 18, 19]
1308
Guido van Rossum805365e2007-05-07 22:24:25 +00001309 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001310 ... # doctest: +NORMALIZE_WHITESPACE
1311 [0, 1, ..., 18, 19]
1312
Thomas Wouters477c8d52006-05-27 19:21:47 +00001313The SKIP flag causes an example to be skipped entirely. I.e., the
1314example is not run. It can be useful in contexts where doctest
1315examples serve as both documentation and test cases, and an example
1316should be included for documentation purposes, but should not be
1317checked (e.g., because its output is random, or depends on resources
1318which would be unavailable.) The SKIP flag can also be used for
1319'commenting out' broken examples.
1320
1321 >>> import unavailable_resource # doctest: +SKIP
1322 >>> unavailable_resource.do_something() # doctest: +SKIP
1323 >>> unavailable_resource.blow_up() # doctest: +SKIP
1324 Traceback (most recent call last):
1325 ...
1326 UncheckedBlowUpError: Nobody checks me.
1327
1328 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001329 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001330 0.721216923889
1331
Edward Loper71f55af2004-08-26 01:41:51 +00001332The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001333and actual outputs to be displayed using a unified diff:
1334
1335 >>> def f(x):
1336 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001337 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001338 ... a
1339 ... B
1340 ... c
1341 ... d
1342 ... f
1343 ... g
1344 ... h
1345 ... '''
1346
1347 >>> # Without the flag:
1348 >>> test = doctest.DocTestFinder().find(f)[0]
1349 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001350 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001351 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001352 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001353 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001354 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001355 Expected:
1356 a
1357 B
1358 c
1359 d
1360 f
1361 g
1362 h
1363 Got:
1364 a
1365 b
1366 c
1367 d
1368 e
1369 f
1370 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001371 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001372
1373 >>> # With the flag:
1374 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001375 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001376 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001377 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001378 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001379 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001380 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001381 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001382 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001383 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001384 a
1385 -B
1386 +b
1387 c
1388 d
1389 +e
1390 f
1391 g
1392 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001393 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001394
Edward Loper71f55af2004-08-26 01:41:51 +00001395The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001396and actual outputs to be displayed using a context diff:
1397
Edward Loper71f55af2004-08-26 01:41:51 +00001398 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001399 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001400 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001401 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001402 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001403 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001404 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001405 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001406 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001407 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001408 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001409 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001410 a
1411 ! B
1412 c
1413 d
1414 f
1415 g
1416 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001417 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001418 a
1419 ! b
1420 c
1421 d
1422 + e
1423 f
1424 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001425 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001426
1427
Edward Loper71f55af2004-08-26 01:41:51 +00001428The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001429used by the popular ndiff.py utility. This does intraline difference
1430marking, as well as interline differences.
1431
1432 >>> def f(x):
1433 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001434 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001435 ... a b c d e f g h i j k 1 m
1436 ... '''
1437 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001438 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001439 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001440 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001441 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001442 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001443 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001444 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001445 Differences (ndiff with -expected +actual):
1446 - a b c d e f g h i j k 1 m
1447 ? ^
1448 + a b c d e f g h i j k l m
1449 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001450 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001451
Ezio Melotti13925002011-03-16 11:05:33 +02001452The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001453failing example:
1454
1455 >>> def f(x):
1456 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001457 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001458 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001459 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001460 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001461 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001462 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001463 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001464 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001465 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001466 ... 500
1467 ... '''
1468 >>> test = doctest.DocTestFinder().find(f)[0]
1469 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1470 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001471 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001472 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001473 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001474 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001475 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001476 Expected:
1477 200
1478 Got:
1479 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001480 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001481
Ezio Melotti13925002011-03-16 11:05:33 +02001482However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001483
1484 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001485 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001486 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001487 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001488 Expecting:
1489 1
1490 ok
1491 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001492 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001493 Expecting:
1494 200
1495 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001496 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001497 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001498 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001499 Expected:
1500 200
1501 Got:
1502 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001503 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001504
R David Murray5a9d7062012-11-21 15:09:21 -05001505The FAIL_FAST flag causes the runner to exit after the first failing example,
1506so subsequent examples are not even attempted:
1507
1508 >>> flags = doctest.FAIL_FAST
1509 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1510 ... # doctest: +ELLIPSIS
1511 **********************************************************************
1512 File ..., line 5, in f
1513 Failed example:
1514 print(2) # first failure
1515 Expected:
1516 200
1517 Got:
1518 2
1519 TestResults(failed=1, attempted=2)
1520
1521Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1522FAIL_FAST only:
1523
1524 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1525 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1526 ... # doctest: +ELLIPSIS
1527 **********************************************************************
1528 File ..., line 5, in f
1529 Failed example:
1530 print(2) # first failure
1531 Expected:
1532 200
1533 Got:
1534 2
1535 TestResults(failed=1, attempted=2)
1536
1537For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1538exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001539
1540 >>> def f(x):
1541 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001542 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001543 ... 1
1544 ... >>> raise ValueError(2) # first failure
1545 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001546 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001547 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001548 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001549 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001550 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001551 ... 500
1552 ... '''
1553 >>> test = doctest.DocTestFinder().find(f)[0]
1554 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1555 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1556 ... # doctest: +ELLIPSIS
1557 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001558 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001559 Failed example:
1560 raise ValueError(2) # first failure
1561 Exception raised:
1562 ...
1563 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001564 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001565 >>> flags = doctest.FAIL_FAST
1566 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1567 ... # doctest: +ELLIPSIS
1568 **********************************************************************
1569 File ..., line 5, in f
1570 Failed example:
1571 raise ValueError(2) # first failure
1572 Exception raised:
1573 ...
1574 ValueError: 2
1575 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001576
Thomas Wouters477c8d52006-05-27 19:21:47 +00001577New option flags can also be registered, via register_optionflag(). Here
1578we reach into doctest's internals a bit.
1579
1580 >>> unlikely = "UNLIKELY_OPTION_NAME"
1581 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1582 False
1583 >>> new_flag_value = doctest.register_optionflag(unlikely)
1584 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1585 True
1586
1587Before 2.4.4/2.5, registering a name more than once erroneously created
1588more than one flag value. Here we verify that's fixed:
1589
1590 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1591 >>> redundant_flag_value == new_flag_value
1592 True
1593
1594Clean up.
1595 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1596
Tim Petersc6cbab02004-08-22 19:43:28 +00001597 """
1598
Tim Peters8485b562004-08-04 18:46:34 +00001599 def option_directives(): r"""
1600Tests of `DocTestRunner`'s option directive mechanism.
1601
Edward Loper74bca7a2004-08-12 02:27:44 +00001602Option directives can be used to turn option flags on or off for a
1603single example. To turn an option on for an example, follow that
1604example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001605
1606 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001607 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001608 ... [0, 1, ..., 9]
1609 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001610 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001611 ... [0, 1, ..., 9]
1612 ... '''
1613 >>> test = doctest.DocTestFinder().find(f)[0]
1614 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001615 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001616 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001617 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001618 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001619 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001620 Expected:
1621 [0, 1, ..., 9]
1622 Got:
1623 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001624 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001625
1626To turn an option off for an example, follow that example with a
1627comment of the form ``# doctest: -OPTION``:
1628
1629 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001630 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001631 ... [0, 1, ..., 9]
1632 ...
1633 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001634 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001635 ... [0, 1, ..., 9]
1636 ... '''
1637 >>> test = doctest.DocTestFinder().find(f)[0]
1638 >>> doctest.DocTestRunner(verbose=False,
1639 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001640 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001641 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001642 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001643 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001644 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001645 Expected:
1646 [0, 1, ..., 9]
1647 Got:
1648 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001649 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001650
1651Option directives affect only the example that they appear with; they
1652do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001653
Edward Loper74bca7a2004-08-12 02:27:44 +00001654 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001655 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001656 ... [0, 1, ..., 9]
1657 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001658 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001659 ... [0, 1, ..., 9]
1660 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001661 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001662 ... [0, 1, ..., 9]
1663 ... '''
1664 >>> test = doctest.DocTestFinder().find(f)[0]
1665 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001666 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001667 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001668 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001669 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001670 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001671 Expected:
1672 [0, 1, ..., 9]
1673 Got:
1674 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001675 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001676 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001677 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001678 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001679 Expected:
1680 [0, 1, ..., 9]
1681 Got:
1682 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001683 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001684
Edward Loper74bca7a2004-08-12 02:27:44 +00001685Multiple options may be modified by a single option directive. They
1686may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001687
1688 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001689 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001690 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001691 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001692 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001693 ... [0, 1, ..., 9]
1694 ... '''
1695 >>> test = doctest.DocTestFinder().find(f)[0]
1696 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001697 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001698 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001699 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001700 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001701 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001702 Expected:
1703 [0, 1, ..., 9]
1704 Got:
1705 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001706 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001707
1708 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001709 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001710 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001711 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001712 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1713 ... [0, 1, ..., 9]
1714 ... '''
1715 >>> test = doctest.DocTestFinder().find(f)[0]
1716 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001717 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001718 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001719 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001720 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001721 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001722 Expected:
1723 [0, 1, ..., 9]
1724 Got:
1725 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001726 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001727
1728 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001729 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001730 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001731 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001732 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1733 ... [0, 1, ..., 9]
1734 ... '''
1735 >>> test = doctest.DocTestFinder().find(f)[0]
1736 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001737 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001738 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001739 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001740 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001741 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001742 Expected:
1743 [0, 1, ..., 9]
1744 Got:
1745 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001746 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001747
1748The option directive may be put on the line following the source, as
1749long as a continuation prompt is used:
1750
1751 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001752 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001753 ... ... # doctest: +ELLIPSIS
1754 ... [0, 1, ..., 9]
1755 ... '''
1756 >>> test = doctest.DocTestFinder().find(f)[0]
1757 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001758 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001759
Edward Loper74bca7a2004-08-12 02:27:44 +00001760For examples with multi-line source, the option directive may appear
1761at the end of any line:
1762
1763 >>> def f(x): r'''
1764 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001765 ... ... print(' ', x, end='', sep='')
1766 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001767 ...
1768 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001769 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1770 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001771 ... '''
1772 >>> test = doctest.DocTestFinder().find(f)[0]
1773 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001774 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001775
1776If more than one line of an example with multi-line source has an
1777option directive, then they are combined:
1778
1779 >>> def f(x): r'''
1780 ... Should fail (option directive not on the last line):
1781 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001782 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001783 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001784 ... '''
1785 >>> test = doctest.DocTestFinder().find(f)[0]
1786 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001787 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001788
1789It is an error to have a comment of the form ``# doctest:`` that is
1790*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1791``OPTION`` is an option that has been registered with
1792`register_option`:
1793
1794 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001795 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001796 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1797 Traceback (most recent call last):
1798 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1799
1800 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001801 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001802 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1803 Traceback (most recent call last):
1804 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1805
1806It is an error to use an option directive on a line that contains no
1807source:
1808
1809 >>> s = '>>> # doctest: +ELLIPSIS'
1810 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1811 Traceback (most recent call last):
1812 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 +00001813"""
1814
1815def test_testsource(): r"""
1816Unit tests for `testsource()`.
1817
1818The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001819test with that name in that module, and converts it to a script. The
1820example code is converted to regular Python code. The surrounding
1821words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001822
1823 >>> import test.test_doctest
1824 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001825 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001826 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001827 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001828 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001829 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001830 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001831 #
Edward Lopera5db6002004-08-12 02:41:30 +00001832 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001833 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001834
1835 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001836 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001837 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001838 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001839 ## 1
1840 ## 2
1841 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001842 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001843
1844 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001845 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001846 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001847 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001848 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001849 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001850 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001851 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001852 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001853"""
1854
1855def test_debug(): r"""
1856
1857Create a docstring that we want to debug:
1858
1859 >>> s = '''
1860 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001861 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001862 ... 12
1863 ... '''
1864
1865Create some fake stdin input, to feed to the debugger:
1866
Tim Peters8485b562004-08-04 18:46:34 +00001867 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001868 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001869
1870Run the debugger on the docstring, and then restore sys.stdin.
1871
Edward Loper2de91ba2004-08-27 02:07:46 +00001872 >>> try: doctest.debug_src(s)
1873 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001875 (Pdb) next
1876 12
Tim Peters8485b562004-08-04 18:46:34 +00001877 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001879 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001880 12
1881 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001882
1883"""
1884
Brett Cannon31f59292011-02-21 19:29:56 +00001885if not hasattr(sys, 'gettrace') or not sys.gettrace():
1886 def test_pdb_set_trace():
1887 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001888
Brett Cannon31f59292011-02-21 19:29:56 +00001889 You can use pdb.set_trace from a doctest. To do so, you must
1890 retrieve the set_trace function from the pdb module at the time
1891 you use it. The doctest module changes sys.stdout so that it can
1892 capture program output. It also temporarily replaces pdb.set_trace
1893 with a version that restores stdout. This is necessary for you to
1894 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001895
Brett Cannon31f59292011-02-21 19:29:56 +00001896 >>> doc = '''
1897 ... >>> x = 42
1898 ... >>> raise Exception('clé')
1899 ... Traceback (most recent call last):
1900 ... Exception: clé
1901 ... >>> import pdb; pdb.set_trace()
1902 ... '''
1903 >>> parser = doctest.DocTestParser()
1904 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1905 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001906
Brett Cannon31f59292011-02-21 19:29:56 +00001907 To demonstrate this, we'll create a fake standard input that
1908 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001909
Brett Cannon31f59292011-02-21 19:29:56 +00001910 >>> real_stdin = sys.stdin
1911 >>> sys.stdin = _FakeInput([
1912 ... 'print(x)', # print data defined by the example
1913 ... 'continue', # stop debugging
1914 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001915
Brett Cannon31f59292011-02-21 19:29:56 +00001916 >>> try: runner.run(test)
1917 ... finally: sys.stdin = real_stdin
1918 --Return--
1919 > <doctest foo-bar@baz[2]>(1)<module>()->None
1920 -> import pdb; pdb.set_trace()
1921 (Pdb) print(x)
1922 42
1923 (Pdb) continue
1924 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001925
Brett Cannon31f59292011-02-21 19:29:56 +00001926 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001927
Brett Cannon31f59292011-02-21 19:29:56 +00001928 >>> def calls_set_trace():
1929 ... y=2
1930 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001931
Brett Cannon31f59292011-02-21 19:29:56 +00001932 >>> doc = '''
1933 ... >>> x=1
1934 ... >>> calls_set_trace()
1935 ... '''
1936 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1937 >>> real_stdin = sys.stdin
1938 >>> sys.stdin = _FakeInput([
1939 ... 'print(y)', # print data defined in the function
1940 ... 'up', # out of function
1941 ... 'print(x)', # print data defined by the example
1942 ... 'continue', # stop debugging
1943 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001944
Brett Cannon31f59292011-02-21 19:29:56 +00001945 >>> try:
1946 ... runner.run(test)
1947 ... finally:
1948 ... sys.stdin = real_stdin
1949 --Return--
Serhiy Storchakae437a102016-04-24 21:41:02 +03001950 > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
Brett Cannon31f59292011-02-21 19:29:56 +00001951 -> import pdb; pdb.set_trace()
1952 (Pdb) print(y)
1953 2
1954 (Pdb) up
1955 > <doctest foo-bar@baz[1]>(1)<module>()
1956 -> calls_set_trace()
1957 (Pdb) print(x)
1958 1
1959 (Pdb) continue
1960 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001961
Brett Cannon31f59292011-02-21 19:29:56 +00001962 During interactive debugging, source code is shown, even for
1963 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001964
Brett Cannon31f59292011-02-21 19:29:56 +00001965 >>> doc = '''
1966 ... >>> def f(x):
1967 ... ... g(x*2)
1968 ... >>> def g(x):
1969 ... ... print(x+3)
1970 ... ... import pdb; pdb.set_trace()
1971 ... >>> f(3)
1972 ... '''
1973 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1974 >>> real_stdin = sys.stdin
1975 >>> sys.stdin = _FakeInput([
1976 ... 'list', # list source from example 2
1977 ... 'next', # return from g()
1978 ... 'list', # list source from example 1
1979 ... 'next', # return from f()
1980 ... 'list', # list source from example 3
1981 ... 'continue', # stop debugging
1982 ... ''])
1983 >>> try: runner.run(test)
1984 ... finally: sys.stdin = real_stdin
1985 ... # doctest: +NORMALIZE_WHITESPACE
1986 --Return--
1987 > <doctest foo-bar@baz[1]>(3)g()->None
1988 -> import pdb; pdb.set_trace()
1989 (Pdb) list
1990 1 def g(x):
1991 2 print(x+3)
1992 3 -> import pdb; pdb.set_trace()
1993 [EOF]
1994 (Pdb) next
1995 --Return--
1996 > <doctest foo-bar@baz[0]>(2)f()->None
1997 -> g(x*2)
1998 (Pdb) list
1999 1 def f(x):
2000 2 -> g(x*2)
2001 [EOF]
2002 (Pdb) next
2003 --Return--
2004 > <doctest foo-bar@baz[2]>(1)<module>()->None
2005 -> f(3)
2006 (Pdb) list
2007 1 -> f(3)
2008 [EOF]
2009 (Pdb) continue
2010 **********************************************************************
2011 File "foo-bar@baz.py", line 7, in foo-bar@baz
2012 Failed example:
2013 f(3)
2014 Expected nothing
2015 Got:
2016 9
2017 TestResults(failed=1, attempted=3)
2018 """
Jim Fulton356fd192004-08-09 11:34:47 +00002019
Brett Cannon31f59292011-02-21 19:29:56 +00002020 def test_pdb_set_trace_nested():
2021 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00002022
Brett Cannon31f59292011-02-21 19:29:56 +00002023 >>> class C(object):
2024 ... def calls_set_trace(self):
2025 ... y = 1
2026 ... import pdb; pdb.set_trace()
2027 ... self.f1()
2028 ... y = 2
2029 ... def f1(self):
2030 ... x = 1
2031 ... self.f2()
2032 ... x = 2
2033 ... def f2(self):
2034 ... z = 1
2035 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002036
Brett Cannon31f59292011-02-21 19:29:56 +00002037 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002038
Brett Cannon31f59292011-02-21 19:29:56 +00002039 >>> doc = '''
2040 ... >>> a = 1
2041 ... >>> calls_set_trace()
2042 ... '''
2043 >>> parser = doctest.DocTestParser()
2044 >>> runner = doctest.DocTestRunner(verbose=False)
2045 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2046 >>> real_stdin = sys.stdin
2047 >>> sys.stdin = _FakeInput([
2048 ... 'print(y)', # print data defined in the function
2049 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2050 ... 'up', 'print(x)',
2051 ... 'up', 'print(y)',
2052 ... 'up', 'print(foo)',
2053 ... 'continue', # stop debugging
2054 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002055
Brett Cannon31f59292011-02-21 19:29:56 +00002056 >>> try:
2057 ... runner.run(test)
2058 ... finally:
2059 ... sys.stdin = real_stdin
2060 ... # doctest: +REPORT_NDIFF
2061 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2062 -> self.f1()
2063 (Pdb) print(y)
2064 1
2065 (Pdb) step
2066 --Call--
2067 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2068 -> def f1(self):
2069 (Pdb) step
2070 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2071 -> x = 1
2072 (Pdb) step
2073 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2074 -> self.f2()
2075 (Pdb) step
2076 --Call--
2077 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2078 -> def f2(self):
2079 (Pdb) step
2080 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2081 -> z = 1
2082 (Pdb) step
2083 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2084 -> z = 2
2085 (Pdb) print(z)
2086 1
2087 (Pdb) up
2088 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2089 -> self.f2()
2090 (Pdb) print(x)
2091 1
2092 (Pdb) up
2093 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2094 -> self.f1()
2095 (Pdb) print(y)
2096 1
2097 (Pdb) up
2098 > <doctest foo-bar@baz[1]>(1)<module>()
2099 -> calls_set_trace()
2100 (Pdb) print(foo)
2101 *** NameError: name 'foo' is not defined
2102 (Pdb) continue
2103 TestResults(failed=0, attempted=2)
2104 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002105
Tim Peters19397e52004-08-06 22:02:59 +00002106def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002107 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002108
2109 We create a Suite by providing a module. A module can be provided
2110 by passing a module object:
2111
2112 >>> import unittest
2113 >>> import test.sample_doctest
2114 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2115 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002116 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002117
2118 We can also supply the module by name:
2119
2120 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2121 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002122 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002123
R David Murray5abd76a2012-09-10 10:15:58 -04002124 The module need not contain any doctest examples:
2125
2126 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2127 >>> suite.run(unittest.TestResult())
2128 <unittest.result.TestResult run=0 errors=0 failures=0>
2129
R David Murray1976d9b2014-04-14 20:28:36 -04002130 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002131
R David Murray1976d9b2014-04-14 20:28:36 -04002132 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002133 >>> suite.run(unittest.TestResult())
2134 <unittest.result.TestResult run=0 errors=0 failures=0>
2135
Tim Peters19397e52004-08-06 22:02:59 +00002136 We can use the current module:
2137
2138 >>> suite = test.sample_doctest.test_suite()
2139 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002140 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002141
R David Murray1976d9b2014-04-14 20:28:36 -04002142 We can also provide a DocTestFinder:
2143
2144 >>> finder = doctest.DocTestFinder()
2145 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2146 ... test_finder=finder)
2147 >>> suite.run(unittest.TestResult())
2148 <unittest.result.TestResult run=9 errors=0 failures=4>
2149
2150 The DocTestFinder need not return any tests:
2151
2152 >>> finder = doctest.DocTestFinder()
2153 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2154 ... test_finder=finder)
2155 >>> suite.run(unittest.TestResult())
2156 <unittest.result.TestResult run=0 errors=0 failures=0>
2157
Tim Peters19397e52004-08-06 22:02:59 +00002158 We can supply global variables. If we pass globs, they will be
2159 used instead of the module globals. Here we'll pass an empty
2160 globals, triggering an extra error:
2161
2162 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2163 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002164 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002165
2166 Alternatively, we can provide extra globals. Here we'll make an
2167 error go away by providing an extra global variable:
2168
2169 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2170 ... extraglobs={'y': 1})
2171 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002172 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002173
2174 You can pass option flags. Here we'll cause an extra error
2175 by disabling the blank-line feature:
2176
2177 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002178 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002179 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002180 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002181
Tim Peters1e277ee2004-08-07 05:37:52 +00002182 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002183
Jim Fultonf54bad42004-08-28 14:57:56 +00002184 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002185 ... import test.test_doctest
2186 ... test.test_doctest.sillySetup = True
2187
Jim Fultonf54bad42004-08-28 14:57:56 +00002188 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002189 ... import test.test_doctest
2190 ... del test.test_doctest.sillySetup
2191
2192 Here, we installed a silly variable that the test expects:
2193
2194 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2195 ... setUp=setUp, tearDown=tearDown)
2196 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002197 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002198
2199 But the tearDown restores sanity:
2200
2201 >>> import test.test_doctest
2202 >>> test.test_doctest.sillySetup
2203 Traceback (most recent call last):
2204 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002205 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002206
Berker Peksag4882cac2015-04-14 09:30:01 +03002207 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002208 we'll use the setUp function to supply the missing variable y:
2209
2210 >>> def setUp(test):
2211 ... test.globs['y'] = 1
2212
2213 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2214 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002215 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002216
2217 Here, we didn't need to use a tearDown function because we
2218 modified the test globals, which are a copy of the
2219 sample_doctest module dictionary. The test globals are
2220 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002221 """
2222
2223def test_DocFileSuite():
2224 """We can test tests found in text files using a DocFileSuite.
2225
2226 We create a suite by providing the names of one or more text
2227 files that include examples:
2228
2229 >>> import unittest
2230 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002231 ... 'test_doctest2.txt',
2232 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002233 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002234 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002235
2236 The test files are looked for in the directory containing the
2237 calling module. A package keyword argument can be provided to
2238 specify a different relative location.
2239
2240 >>> import unittest
2241 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2242 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002243 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002244 ... package='test')
2245 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002246 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002247
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002248 Support for using a package's __loader__.get_data() is also
2249 provided.
2250
2251 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002252 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002253 >>> if not hasattr(test, '__loader__'):
2254 ... test.__loader__ = pkgutil.get_loader(test)
2255 ... added_loader = True
2256 >>> try:
2257 ... suite = doctest.DocFileSuite('test_doctest.txt',
2258 ... 'test_doctest2.txt',
2259 ... 'test_doctest4.txt',
2260 ... package='test')
2261 ... suite.run(unittest.TestResult())
2262 ... finally:
2263 ... if added_loader:
2264 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002265 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002266
Edward Loper0273f5b2004-09-18 20:27:04 +00002267 '/' should be used as a path separator. It will be converted
2268 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002269
2270 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2271 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002272 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002273
Edward Loper0273f5b2004-09-18 20:27:04 +00002274 If DocFileSuite is used from an interactive session, then files
2275 are resolved relative to the directory of sys.argv[0]:
2276
Christian Heimes45f9af32007-11-27 21:50:00 +00002277 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002278 >>> save_argv = sys.argv
2279 >>> sys.argv = [test.test_doctest.__file__]
2280 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002281 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002282 >>> sys.argv = save_argv
2283
Edward Loper052d0cd2004-09-19 17:19:33 +00002284 By setting `module_relative=False`, os-specific paths may be
2285 used (including absolute paths and paths relative to the
2286 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002287
2288 >>> # Get the absolute path of the test package.
2289 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2290 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2291
2292 >>> # Use it to find the absolute path of test_doctest.txt.
2293 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2294
Edward Loper052d0cd2004-09-19 17:19:33 +00002295 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002296 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002297 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002298
Edward Loper052d0cd2004-09-19 17:19:33 +00002299 It is an error to specify `package` when `module_relative=False`:
2300
2301 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2302 ... package='test')
2303 Traceback (most recent call last):
2304 ValueError: Package may only be specified for module-relative paths.
2305
Tim Peters19397e52004-08-06 22:02:59 +00002306 You can specify initial global variables:
2307
2308 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2309 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002310 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002311 ... globs={'favorite_color': 'blue'})
2312 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002313 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002314
2315 In this case, we supplied a missing favorite color. You can
2316 provide doctest options:
2317
2318 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2319 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002320 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002321 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2322 ... globs={'favorite_color': 'blue'})
2323 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002324 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002325
2326 And, you can provide setUp and tearDown functions:
2327
Jim Fultonf54bad42004-08-28 14:57:56 +00002328 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002329 ... import test.test_doctest
2330 ... test.test_doctest.sillySetup = True
2331
Jim Fultonf54bad42004-08-28 14:57:56 +00002332 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002333 ... import test.test_doctest
2334 ... del test.test_doctest.sillySetup
2335
2336 Here, we installed a silly variable that the test expects:
2337
2338 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2339 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002340 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002341 ... setUp=setUp, tearDown=tearDown)
2342 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002343 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002344
2345 But the tearDown restores sanity:
2346
2347 >>> import test.test_doctest
2348 >>> test.test_doctest.sillySetup
2349 Traceback (most recent call last):
2350 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002351 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002352
Berker Peksag4882cac2015-04-14 09:30:01 +03002353 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002354 Here, we'll use a setUp function to set the favorite color in
2355 test_doctest.txt:
2356
2357 >>> def setUp(test):
2358 ... test.globs['favorite_color'] = 'blue'
2359
2360 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2361 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002362 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002363
2364 Here, we didn't need to use a tearDown function because we
2365 modified the test globals. The test globals are
2366 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002367
Fred Drake7c404a42004-12-21 23:46:34 +00002368 Tests in a file run using `DocFileSuite` can also access the
2369 `__file__` global, which is set to the name of the file
2370 containing the tests:
2371
Benjamin Petersonab078e92016-07-13 21:13:29 -07002372 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
Fred Drake7c404a42004-12-21 23:46:34 +00002373 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002374 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002375
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002376 If the tests contain non-ASCII characters, we have to specify which
2377 encoding the file is encoded with. We do so by using the `encoding`
2378 parameter:
2379
2380 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2381 ... 'test_doctest2.txt',
2382 ... 'test_doctest4.txt',
2383 ... encoding='utf-8')
2384 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002385 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002386
Jim Fultonf54bad42004-08-28 14:57:56 +00002387 """
Tim Peters19397e52004-08-06 22:02:59 +00002388
Jim Fulton07a349c2004-08-22 14:10:00 +00002389def test_trailing_space_in_test():
2390 """
Tim Petersa7def722004-08-23 22:13:22 +00002391 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002392
Jim Fulton07a349c2004-08-22 14:10:00 +00002393 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002394 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002395 foo \n
2396 """
Tim Peters19397e52004-08-06 22:02:59 +00002397
Yury Selivanovb532df62014-12-08 15:00:05 -05002398class Wrapper:
2399 def __init__(self, func):
2400 self.func = func
2401 functools.update_wrapper(self, func)
2402
2403 def __call__(self, *args, **kwargs):
2404 self.func(*args, **kwargs)
2405
2406@Wrapper
2407def test_look_in_unwrapped():
2408 """
2409 Docstrings in wrapped functions must be detected as well.
2410
2411 >>> 'one other test'
2412 'one other test'
2413 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002414
2415def test_unittest_reportflags():
2416 """Default unittest reporting flags can be set to control reporting
2417
2418 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2419 only the first failure of each test. First, we'll look at the
2420 output without the flag. The file test_doctest.txt file has two
2421 tests. They both fail if blank lines are disabled:
2422
2423 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2424 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2425 >>> import unittest
2426 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002427 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002428 Traceback ...
2429 Failed example:
2430 favorite_color
2431 ...
2432 Failed example:
2433 if 1:
2434 ...
2435
2436 Note that we see both failures displayed.
2437
2438 >>> old = doctest.set_unittest_reportflags(
2439 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2440
2441 Now, when we run the test:
2442
2443 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002444 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002445 Traceback ...
2446 Failed example:
2447 favorite_color
2448 Exception raised:
2449 ...
2450 NameError: name 'favorite_color' is not defined
2451 <BLANKLINE>
2452 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002453
Jim Fultonf54bad42004-08-28 14:57:56 +00002454 We get only the first failure.
2455
2456 If we give any reporting options when we set up the tests,
2457 however:
2458
2459 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2460 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2461
2462 Then the default eporting options are ignored:
2463
2464 >>> result = suite.run(unittest.TestResult())
Pablo Galindoc5dc60e2019-01-10 14:29:40 +00002465
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302466 *NOTE*: These doctest are intentionally not placed in raw string to depict
2467 the trailing whitespace using `\x20` in the diff below.
2468
Guido van Rossum7131f842007-02-09 20:13:25 +00002469 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002470 Traceback ...
2471 Failed example:
2472 favorite_color
2473 ...
2474 Failed example:
2475 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002476 print('a')
2477 print()
2478 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002479 Differences (ndiff with -expected +actual):
2480 a
2481 - <BLANKLINE>
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302482 +\x20
Jim Fultonf54bad42004-08-28 14:57:56 +00002483 b
2484 <BLANKLINE>
2485 <BLANKLINE>
2486
2487
2488 Test runners can restore the formatting flags after they run:
2489
2490 >>> ignored = doctest.set_unittest_reportflags(old)
2491
2492 """
2493
Edward Loper052d0cd2004-09-19 17:19:33 +00002494def test_testfile(): r"""
2495Tests for the `testfile()` function. This function runs all the
Min ho Kimc4cacc82019-07-31 08:16:13 +10002496doctest examples in a given file. In its simple invocation, it is
Edward Loper052d0cd2004-09-19 17:19:33 +00002497called with the name of a file, which is taken to be relative to the
2498calling module. The return value is (#failures, #tests).
2499
Florent Xicluna59250852010-02-27 14:21:57 +00002500We don't want `-v` in sys.argv for these tests.
2501
2502 >>> save_argv = sys.argv
2503 >>> if '-v' in sys.argv:
2504 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2505
2506
Edward Loper052d0cd2004-09-19 17:19:33 +00002507 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2508 **********************************************************************
2509 File "...", line 6, in test_doctest.txt
2510 Failed example:
2511 favorite_color
2512 Exception raised:
2513 ...
2514 NameError: name 'favorite_color' is not defined
2515 **********************************************************************
2516 1 items had failures:
2517 1 of 2 in test_doctest.txt
2518 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002519 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002520 >>> doctest.master = None # Reset master.
2521
2522(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002523`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002524same name.)
2525
2526Globals may be specified with the `globs` and `extraglobs` parameters:
2527
2528 >>> globs = {'favorite_color': 'blue'}
2529 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002530 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002531 >>> doctest.master = None # Reset master.
2532
2533 >>> extraglobs = {'favorite_color': 'red'}
2534 >>> doctest.testfile('test_doctest.txt', globs=globs,
2535 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2536 **********************************************************************
2537 File "...", line 6, in test_doctest.txt
2538 Failed example:
2539 favorite_color
2540 Expected:
2541 'blue'
2542 Got:
2543 'red'
2544 **********************************************************************
2545 1 items had failures:
2546 1 of 2 in test_doctest.txt
2547 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002548 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002549 >>> doctest.master = None # Reset master.
2550
2551The file may be made relative to a given module or package, using the
2552optional `module_relative` parameter:
2553
2554 >>> doctest.testfile('test_doctest.txt', globs=globs,
2555 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002556 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002557 >>> doctest.master = None # Reset master.
2558
Ezio Melotti13925002011-03-16 11:05:33 +02002559Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002560
2561 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2562 Trying:
2563 favorite_color
2564 Expecting:
2565 'blue'
2566 ok
2567 Trying:
2568 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002569 print('a')
2570 print()
2571 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002572 Expecting:
2573 a
2574 <BLANKLINE>
2575 b
2576 ok
2577 1 items passed all tests:
2578 2 tests in test_doctest.txt
2579 2 tests in 1 items.
2580 2 passed and 0 failed.
2581 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002582 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002583 >>> doctest.master = None # Reset master.
2584
2585The name of the test may be specified with the optional `name`
2586parameter:
2587
2588 >>> doctest.testfile('test_doctest.txt', name='newname')
2589 ... # doctest: +ELLIPSIS
2590 **********************************************************************
2591 File "...", line 6, in newname
2592 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002593 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002594 >>> doctest.master = None # Reset master.
2595
Ezio Melotti13925002011-03-16 11:05:33 +02002596The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002597parameter:
2598
2599 >>> doctest.testfile('test_doctest.txt', report=False)
2600 ... # doctest: +ELLIPSIS
2601 **********************************************************************
2602 File "...", line 6, in test_doctest.txt
2603 Failed example:
2604 favorite_color
2605 Exception raised:
2606 ...
2607 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002608 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002609 >>> doctest.master = None # Reset master.
2610
2611The optional keyword argument `raise_on_error` can be used to raise an
2612exception on the first error (which may be useful for postmortem
2613debugging):
2614
2615 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2616 ... # doctest: +ELLIPSIS
2617 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002618 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002619 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002620
2621If the tests contain non-ASCII characters, the tests might fail, since
2622it's unknown which encoding is used. The encoding can be specified
2623using the optional keyword argument `encoding`:
2624
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002625 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002626 **********************************************************************
2627 File "...", line 7, in test_doctest4.txt
2628 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002629 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002630 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002631 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002632 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002633 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002634 **********************************************************************
2635 ...
2636 **********************************************************************
2637 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002638 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002639 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002640 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002641 >>> doctest.master = None # Reset master.
2642
2643 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002644 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002645 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002646
2647Test the verbose output:
2648
2649 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2650 Trying:
2651 'föö'
2652 Expecting:
2653 'f\xf6\xf6'
2654 ok
2655 Trying:
2656 'bÄ…r'
2657 Expecting:
2658 'b\u0105r'
2659 ok
2660 1 items passed all tests:
2661 2 tests in test_doctest4.txt
2662 2 tests in 1 items.
2663 2 passed and 0 failed.
2664 Test passed.
2665 TestResults(failed=0, attempted=2)
2666 >>> doctest.master = None # Reset master.
2667 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002668"""
2669
Peter Donise0b81012020-03-26 11:53:16 -04002670class TestImporter(importlib.abc.MetaPathFinder, importlib.abc.ResourceLoader):
2671
2672 def find_spec(self, fullname, path, target=None):
2673 return importlib.util.spec_from_file_location(fullname, path, loader=self)
2674
2675 def get_data(self, path):
2676 with open(path, mode='rb') as f:
2677 return f.read()
2678
2679class TestHook:
2680
2681 def __init__(self, pathdir):
2682 self.sys_path = sys.path[:]
2683 self.meta_path = sys.meta_path[:]
2684 self.path_hooks = sys.path_hooks[:]
2685 sys.path.append(pathdir)
2686 sys.path_importer_cache.clear()
2687 self.modules_before = sys.modules.copy()
2688 self.importer = TestImporter()
2689 sys.meta_path.append(self.importer)
2690
2691 def remove(self):
2692 sys.path[:] = self.sys_path
2693 sys.meta_path[:] = self.meta_path
2694 sys.path_hooks[:] = self.path_hooks
2695 sys.path_importer_cache.clear()
2696 sys.modules.clear()
2697 sys.modules.update(self.modules_before)
2698
2699
2700@contextlib.contextmanager
2701def test_hook(pathdir):
2702 hook = TestHook(pathdir)
2703 try:
2704 yield hook
2705 finally:
2706 hook.remove()
2707
2708
R David Murrayb48cb292014-10-02 22:42:42 -04002709def test_lineendings(): r"""
Peter Donise0b81012020-03-26 11:53:16 -04002710*nix systems use \n line endings, while Windows systems use \r\n, and
2711old Mac systems used \r, which Python still recognizes as a line ending. Python
R David Murrayb48cb292014-10-02 22:42:42 -04002712handles this using universal newline mode for reading files. Let's make
2713sure doctest does so (issue 8473) by creating temporary test files using each
Peter Donise0b81012020-03-26 11:53:16 -04002714of the three line disciplines. At least one will not match either the universal
2715newline \n or os.linesep for the platform the test is run on.
R David Murrayb48cb292014-10-02 22:42:42 -04002716
2717Windows line endings first:
2718
2719 >>> import tempfile, os
2720 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002721 >>> with open(fn, 'wb') as f:
2722 ... 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 -04002723 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002724 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002725 TestResults(failed=0, attempted=1)
2726 >>> os.remove(fn)
2727
2728And now *nix line endings:
2729
2730 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002731 >>> with open(fn, 'wb') as f:
2732 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002733 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002734 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002735 TestResults(failed=0, attempted=1)
2736 >>> os.remove(fn)
2737
Peter Donise0b81012020-03-26 11:53:16 -04002738And finally old Mac line endings:
2739
2740 >>> fn = tempfile.mktemp()
2741 >>> with open(fn, 'wb') as f:
2742 ... f.write(b'Test:\r\r >>> x = 1 + 1\r\rDone.\r')
2743 30
2744 >>> doctest.testfile(fn, module_relative=False, verbose=False)
2745 TestResults(failed=0, attempted=1)
2746 >>> os.remove(fn)
2747
2748Now we test with a package loader that has a get_data method, since that
2749bypasses the standard universal newline handling so doctest has to do the
2750newline conversion itself; let's make sure it does so correctly (issue 1812).
2751We'll write a file inside the package that has all three kinds of line endings
2752in it, and use a package hook to install a custom loader; on any platform,
2753at least one of the line endings will raise a ValueError for inconsistent
2754whitespace if doctest does not correctly do the newline conversion.
2755
2756 >>> dn = tempfile.mkdtemp()
2757 >>> pkg = os.path.join(dn, "doctest_testpkg")
2758 >>> os.mkdir(pkg)
2759 >>> support.create_empty_file(os.path.join(pkg, "__init__.py"))
2760 >>> fn = os.path.join(pkg, "doctest_testfile.txt")
2761 >>> with open(fn, 'wb') as f:
2762 ... f.write(
2763 ... b'Test:\r\n\r\n'
2764 ... b' >>> x = 1 + 1\r\n\r\n'
2765 ... b'Done.\r\n'
2766 ... b'Test:\n\n'
2767 ... b' >>> x = 1 + 1\n\n'
2768 ... b'Done.\n'
2769 ... b'Test:\r\r'
2770 ... b' >>> x = 1 + 1\r\r'
2771 ... b'Done.\r'
2772 ... )
2773 95
2774 >>> with test_hook(dn):
2775 ... doctest.testfile("doctest_testfile.txt", package="doctest_testpkg", verbose=False)
2776 TestResults(failed=0, attempted=3)
2777 >>> shutil.rmtree(dn)
2778
R David Murrayb48cb292014-10-02 22:42:42 -04002779"""
2780
R. David Murray58641de2009-06-12 15:33:19 +00002781def test_testmod(): r"""
2782Tests for the testmod function. More might be useful, but for now we're just
2783testing the case raised by Issue 6195, where trying to doctest a C module would
2784fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2785out of the binary module.
2786
2787 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002788 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002789 TestResults(failed=0, attempted=0)
2790"""
2791
Victor Stinner9d396392010-10-16 21:54:59 +00002792try:
2793 os.fsencode("foo-bär@baz.py")
2794except UnicodeEncodeError:
2795 # Skip the test: the filesystem encoding is unable to encode the filename
2796 pass
2797else:
2798 def test_unicode(): """
2799Check doctest with a non-ascii filename:
2800
2801 >>> doc = '''
2802 ... >>> raise Exception('clé')
2803 ... '''
2804 ...
2805 >>> parser = doctest.DocTestParser()
2806 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2807 >>> test
2808 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2809 >>> runner = doctest.DocTestRunner(verbose=False)
2810 >>> runner.run(test) # doctest: +ELLIPSIS
2811 **********************************************************************
2812 File "foo-bär@baz.py", line 2, in foo-bär@baz
2813 Failed example:
2814 raise Exception('clé')
2815 Exception raised:
2816 Traceback (most recent call last):
2817 File ...
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03002818 exec(compile(example.source, filename, "single",
Victor Stinner9d396392010-10-16 21:54:59 +00002819 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2820 raise Exception('clé')
2821 Exception: clé
2822 TestResults(failed=1, attempted=1)
2823 """
2824
R David Murray5707d502013-06-23 14:24:13 -04002825def test_CLI(): r"""
2826The doctest module can be used to run doctests against an arbitrary file.
2827These tests test this CLI functionality.
2828
2829We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002830to a temp dir to run the command against. Due to a current limitation in
2831script_helpers, though, we need a little utility function to turn the returned
2832output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002833
R David Murray4af68982013-06-25 08:11:22 -04002834 >>> def normalize(s):
2835 ... return '\n'.join(s.decode().splitlines())
2836
R David Murray4af68982013-06-25 08:11:22 -04002837With those preliminaries out of the way, we'll start with a file with two
2838simple tests and no errors. We'll run both the unadorned doctest command, and
2839the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002840
Berker Peksagce643912015-05-06 06:33:17 +03002841 >>> from test.support import script_helper, temp_dir
2842 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002843 ... fn = os.path.join(tmpdir, 'myfile.doc')
2844 ... with open(fn, 'w') as f:
2845 ... _ = f.write('This is a very simple test file.\n')
2846 ... _ = f.write(' >>> 1 + 1\n')
2847 ... _ = f.write(' 2\n')
2848 ... _ = f.write(' >>> "a"\n')
2849 ... _ = f.write(" 'a'\n")
2850 ... _ = f.write('\n')
2851 ... _ = f.write('And that is it.\n')
2852 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002853 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002854 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002855 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002856
2857With no arguments and passing tests, we should get no output:
2858
2859 >>> rc1, out1, err1
2860 (0, b'', b'')
2861
2862With the verbose flag, we should see the test output, but no error output:
2863
2864 >>> rc2, err2
2865 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002866 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002867 Trying:
2868 1 + 1
2869 Expecting:
2870 2
2871 ok
2872 Trying:
2873 "a"
2874 Expecting:
2875 'a'
2876 ok
2877 1 items passed all tests:
2878 2 tests in myfile.doc
2879 2 tests in 1 items.
2880 2 passed and 0 failed.
2881 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002882
2883Now we'll write a couple files, one with three tests, the other a python module
2884with two tests, both of the files having "errors" in the tests that can be made
2885non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2886the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002887allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002888ability to process more than one file on the command line and, since the second
2889file ends in '.py', its handling of python module files (as opposed to straight
2890text files).
2891
Berker Peksagce643912015-05-06 06:33:17 +03002892 >>> from test.support import script_helper, temp_dir
2893 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002894 ... fn = os.path.join(tmpdir, 'myfile.doc')
2895 ... with open(fn, 'w') as f:
2896 ... _ = f.write('This is another simple test file.\n')
2897 ... _ = f.write(' >>> 1 + 1\n')
2898 ... _ = f.write(' 2\n')
2899 ... _ = f.write(' >>> "abcdef"\n')
2900 ... _ = f.write(" 'a...f'\n")
2901 ... _ = f.write(' >>> "ajkml"\n')
2902 ... _ = f.write(" 'a...l'\n")
2903 ... _ = f.write('\n')
2904 ... _ = f.write('And that is it.\n')
2905 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2906 ... with open(fn2, 'w') as f:
2907 ... _ = f.write('def test_func():\n')
2908 ... _ = f.write(' \"\"\"\n')
2909 ... _ = f.write(' This is simple python test function.\n')
2910 ... _ = f.write(' >>> 1 + 1\n')
2911 ... _ = f.write(' 2\n')
2912 ... _ = f.write(' >>> "abc def"\n')
2913 ... _ = f.write(" 'abc def'\n")
2914 ... _ = f.write("\n")
2915 ... _ = f.write(' \"\"\"\n')
R David Murray5707d502013-06-23 14:24:13 -04002916 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002917 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002918 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002919 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002920 ... rc3, out3, err3 = script_helper.assert_python_ok(
2921 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002922 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002923 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002924 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002925 ... rc5, out5, err5 = script_helper.assert_python_ok(
2926 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002927 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002928
2929Our first test run will show the errors from the first file (doctest stops if a
2930file has errors). Note that doctest test-run error output appears on stdout,
2931not stderr:
2932
2933 >>> rc1, err1
2934 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002935 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002936 **********************************************************************
2937 File "...myfile.doc", line 4, in myfile.doc
2938 Failed example:
2939 "abcdef"
2940 Expected:
2941 'a...f'
2942 Got:
2943 'abcdef'
2944 **********************************************************************
2945 File "...myfile.doc", line 6, in myfile.doc
2946 Failed example:
2947 "ajkml"
2948 Expected:
2949 'a...l'
2950 Got:
2951 'ajkml'
2952 **********************************************************************
2953 1 items had failures:
2954 2 of 3 in myfile.doc
2955 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002956
2957With -o ELLIPSIS specified, the second run, against just the first file, should
2958produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2959should the third, which ran against both files:
2960
2961 >>> rc2, out2, err2
2962 (0, b'', b'')
2963 >>> rc3, out3, err3
2964 (0, b'', b'')
2965
2966The fourth run uses FAIL_FAST, so we should see only one error:
2967
2968 >>> rc4, err4
2969 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002970 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002971 **********************************************************************
2972 File "...myfile.doc", line 4, in myfile.doc
2973 Failed example:
2974 "abcdef"
2975 Expected:
2976 'a...f'
2977 Got:
2978 'abcdef'
2979 **********************************************************************
2980 1 items had failures:
2981 1 of 2 in myfile.doc
2982 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002983
2984The fifth test uses verbose with the two options, so we should get verbose
2985success output for the tests in both files:
2986
2987 >>> rc5, err5
2988 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002989 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002990 Trying:
2991 1 + 1
2992 Expecting:
2993 2
2994 ok
2995 Trying:
2996 "abcdef"
2997 Expecting:
2998 'a...f'
2999 ok
3000 Trying:
3001 "ajkml"
3002 Expecting:
3003 'a...l'
3004 ok
3005 1 items passed all tests:
3006 3 tests in myfile.doc
3007 3 tests in 1 items.
3008 3 passed and 0 failed.
3009 Test passed.
3010 Trying:
3011 1 + 1
3012 Expecting:
3013 2
3014 ok
3015 Trying:
3016 "abc def"
3017 Expecting:
3018 'abc def'
3019 ok
3020 1 items had no tests:
3021 myfile2
3022 1 items passed all tests:
3023 2 tests in myfile2.test_func
3024 2 tests in 2 items.
3025 2 passed and 0 failed.
3026 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04003027
3028We should also check some typical error cases.
3029
3030Invalid file name:
3031
3032 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03003033 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04003034 >>> rc, out
3035 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04003036 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003037 Traceback (most recent call last):
3038 ...
3039 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
3040
3041Invalid doctest option:
3042
3043 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03003044 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04003045 >>> rc, out
3046 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04003047 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003048 usage...invalid...nosuchoption...
3049
3050"""
3051
Sanyam Khuranacbb16452019-01-09 19:08:38 +05303052def test_no_trailing_whitespace_stripping():
3053 r"""
3054 The fancy reports had a bug for a long time where any trailing whitespace on
3055 the reported diff lines was stripped, making it impossible to see the
3056 differences in line reported as different that differed only in the amount of
3057 trailing whitespace. The whitespace still isn't particularly visible unless
3058 you use NDIFF, but at least it is now there to be found.
3059
3060 *NOTE*: This snippet was intentionally put inside a raw string to get rid of
3061 leading whitespace error in executing the example below
3062
3063 >>> def f(x):
3064 ... r'''
3065 ... >>> print('\n'.join(['a ', 'b']))
3066 ... a
3067 ... b
3068 ... '''
3069 """
3070 """
3071 *NOTE*: These doctest are not placed in raw string to depict the trailing whitespace
3072 using `\x20`
3073
3074 >>> test = doctest.DocTestFinder().find(f)[0]
3075 >>> flags = doctest.REPORT_NDIFF
3076 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
3077 ... # doctest: +ELLIPSIS
3078 **********************************************************************
3079 File ..., line 3, in f
3080 Failed example:
3081 print('\n'.join(['a ', 'b']))
3082 Differences (ndiff with -expected +actual):
3083 - a
3084 + a
3085 b
3086 TestResults(failed=1, attempted=1)
3087
3088 *NOTE*: `\x20` is for checking the trailing whitespace on the +a line above.
3089 We cannot use actual spaces there, as a commit hook prevents from committing
3090 patches that contain trailing whitespace. More info on Issue 24746.
3091 """
3092
Tim Peters8485b562004-08-04 18:46:34 +00003093######################################################################
3094## Main
3095######################################################################
3096
3097def test_main():
3098 # Check the doctest cases in doctest itself:
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02003099 ret = support.run_doctest(doctest, verbosity=True)
Victor Stinner931602a2016-03-25 12:48:17 +01003100
Tim Peters8485b562004-08-04 18:46:34 +00003101 # Check the doctest cases defined here:
3102 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003103 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00003104
Jason R. Coombsb9650a02018-03-05 18:29:08 -05003105 # Run unittests
3106 support.run_unittest(__name__)
3107
3108
Tim Peters8485b562004-08-04 18:46:34 +00003109def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00003110 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01003111 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00003112 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00003113 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00003114 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003115 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00003116 r.write_results(show_missing=True, summary=True,
3117 coverdir=coverdir)
3118
3119if __name__ == '__main__':
3120 if '-c' in sys.argv:
3121 test_coverage('/tmp/doctest.cover')
3122 else:
3123 test_main()