blob: 8d9f8729687754dd979ef0b4687ec256be1f4f78 [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Yury Selivanovb532df62014-12-08 15:00:05 -05007import functools
Victor Stinner9d396392010-10-16 21:54:59 +00008import os
Brett Cannon31f59292011-02-21 19:29:56 +00009import sys
Jason R. Coombsb9650a02018-03-05 18:29:08 -050010import importlib
Peter Donise0b81012020-03-26 11:53:16 -040011import importlib.abc
12import importlib.util
Jason R. Coombsb9650a02018-03-05 18:29:08 -050013import unittest
Nick Coghland5d9e022018-03-25 23:03:10 +100014import tempfile
Peter Donise0b81012020-03-26 11:53:16 -040015import shutil
16import contextlib
Florent Xiclunadc6f2d02010-04-02 19:25:32 +000017
Nick Coghlanf088e5e2008-12-14 11:50:48 +000018# NOTE: There are some additional tests relating to interaction with
19# zipimport in the test_zipimport_support test module.
20
Tim Peters8485b562004-08-04 18:46:34 +000021######################################################################
22## Sample Objects (used by test cases)
23######################################################################
24
25def sample_func(v):
26 """
Tim Peters19397e52004-08-06 22:02:59 +000027 Blah blah
28
Guido van Rossum7131f842007-02-09 20:13:25 +000029 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000030 44
Tim Peters19397e52004-08-06 22:02:59 +000031
32 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000033 """
34 return v+v
35
36class SampleClass:
37 """
Guido van Rossum7131f842007-02-09 20:13:25 +000038 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000039 1
Edward Loper4ae900f2004-09-21 03:20:34 +000040
41 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
42 >>>
43 ...
44
45 Multiline example:
46 >>> sc = SampleClass(3)
47 >>> for i in range(10):
48 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000049 ... print(' ', sc.get(), sep='', end='')
50 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000051 """
52 def __init__(self, val):
53 """
Guido van Rossum7131f842007-02-09 20:13:25 +000054 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000055 12
56 """
57 self.val = val
58
59 def double(self):
60 """
Guido van Rossum7131f842007-02-09 20:13:25 +000061 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000062 24
63 """
64 return SampleClass(self.val + self.val)
65
66 def get(self):
67 """
Guido van Rossum7131f842007-02-09 20:13:25 +000068 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000069 -5
70 """
71 return self.val
72
73 def a_staticmethod(v):
74 """
Guido van Rossum7131f842007-02-09 20:13:25 +000075 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000076 11
77 """
78 return v+1
79 a_staticmethod = staticmethod(a_staticmethod)
80
81 def a_classmethod(cls, v):
82 """
Guido van Rossum7131f842007-02-09 20:13:25 +000083 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000084 12
Guido van Rossum7131f842007-02-09 20:13:25 +000085 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000086 12
87 """
88 return v+2
89 a_classmethod = classmethod(a_classmethod)
90
91 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000092 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000093 22
94 """)
95
96 class NestedClass:
97 """
98 >>> x = SampleClass.NestedClass(5)
99 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +0000100 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +0000101 25
102 """
103 def __init__(self, val=0):
104 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000105 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +0000106 0
107 """
108 self.val = val
109 def square(self):
110 return SampleClass.NestedClass(self.val*self.val)
111 def get(self):
112 return self.val
113
114class SampleNewStyleClass(object):
115 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000116 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000117 1
118 2
119 3
120 """
121 def __init__(self, val):
122 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000123 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000124 12
125 """
126 self.val = val
127
128 def double(self):
129 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000130 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000131 24
132 """
133 return SampleNewStyleClass(self.val + self.val)
134
135 def get(self):
136 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000137 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000138 -5
139 """
140 return self.val
141
142######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000143## Fake stdin (for testing interactive debugging)
144######################################################################
145
146class _FakeInput:
147 """
148 A fake input stream for pdb's interactive debugger. Whenever a
149 line is read, print it (to simulate the user typing it), and then
150 return it. The set of lines to return is specified in the
151 constructor; they should not have trailing newlines.
152 """
153 def __init__(self, lines):
154 self.lines = lines
155
156 def readline(self):
157 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000158 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000159 return line+'\n'
160
161######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000162## Test Cases
163######################################################################
164
165def test_Example(): r"""
166Unit tests for the `Example` class.
167
Edward Lopera6b68322004-08-26 00:05:43 +0000168Example is a simple container class that holds:
169 - `source`: A source string.
170 - `want`: An expected output string.
171 - `exc_msg`: An expected exception message string (or None if no
172 exception is expected).
173 - `lineno`: A line number (within the docstring).
174 - `indent`: The example's indentation in the input string.
175 - `options`: An option dictionary, mapping option flags to True or
176 False.
Tim Peters8485b562004-08-04 18:46:34 +0000177
Edward Lopera6b68322004-08-26 00:05:43 +0000178These attributes are set by the constructor. `source` and `want` are
179required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000180
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000181 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000182 >>> (example.source, example.want, example.exc_msg,
183 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000184 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000185
186The first three attributes (`source`, `want`, and `exc_msg`) may be
187specified positionally; the remaining arguments should be specified as
188keyword arguments:
189
190 >>> exc_msg = 'IndexError: pop from an empty list'
191 >>> example = doctest.Example('[].pop()', '', exc_msg,
192 ... lineno=5, indent=4,
193 ... options={doctest.ELLIPSIS: True})
194 >>> (example.source, example.want, example.exc_msg,
195 ... example.lineno, example.indent, example.options)
196 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
197
198The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000199
Tim Petersbb431472004-08-09 03:51:46 +0000200 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000201 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000202 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000203 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000204
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000205 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000206 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000207 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000208
Tim Petersbb431472004-08-09 03:51:46 +0000209 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000210 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000211 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000212 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000213
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000214 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000215 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000216 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000217
Edward Lopera6b68322004-08-26 00:05:43 +0000218 Empty source string (which should never appear in real examples)
219 >>> e = doctest.Example('', '')
220 >>> e.source, e.want
221 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000222
Edward Lopera6b68322004-08-26 00:05:43 +0000223The constructor normalizes the `want` string to end in a newline,
224unless it's the empty string:
225
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000226 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000227 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000228 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000229
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000230 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000231 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000232 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000233
Edward Lopera6b68322004-08-26 00:05:43 +0000234 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000235 >>> e.source, e.want
236 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000237
238The constructor normalizes the `exc_msg` string to end in a newline,
239unless it's `None`:
240
241 Message spans one line
242 >>> exc_msg = 'IndexError: pop from an empty list'
243 >>> e = doctest.Example('[].pop()', '', exc_msg)
244 >>> e.exc_msg
245 'IndexError: pop from an empty list\n'
246
247 >>> exc_msg = 'IndexError: pop from an empty list\n'
248 >>> e = doctest.Example('[].pop()', '', exc_msg)
249 >>> e.exc_msg
250 'IndexError: pop from an empty list\n'
251
252 Message spans multiple lines
253 >>> exc_msg = 'ValueError: 1\n 2'
254 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
255 >>> e.exc_msg
256 'ValueError: 1\n 2\n'
257
258 >>> exc_msg = 'ValueError: 1\n 2\n'
259 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
260 >>> e.exc_msg
261 'ValueError: 1\n 2\n'
262
263 Empty (but non-None) exception message (which should never appear
264 in real examples)
265 >>> exc_msg = ''
266 >>> e = doctest.Example('raise X()', '', exc_msg)
267 >>> e.exc_msg
268 '\n'
Antoine Pitrou165b1282011-12-18 20:20:17 +0100269
270Compare `Example`:
271 >>> example = doctest.Example('print 1', '1\n')
272 >>> same_example = doctest.Example('print 1', '1\n')
273 >>> other_example = doctest.Example('print 42', '42\n')
274 >>> example == same_example
275 True
276 >>> example != same_example
277 False
278 >>> hash(example) == hash(same_example)
279 True
280 >>> example == other_example
281 False
282 >>> example != other_example
283 True
Tim Peters8485b562004-08-04 18:46:34 +0000284"""
285
286def test_DocTest(): r"""
287Unit tests for the `DocTest` class.
288
289DocTest is a collection of examples, extracted from a docstring, along
290with information about where the docstring comes from (a name,
291filename, and line number). The docstring is parsed by the `DocTest`
292constructor:
293
294 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000295 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000296 ... 12
297 ...
298 ... Non-example text.
299 ...
R David Murray44b548d2016-09-08 13:59:53 -0400300 ... >>> print('another\\example')
Tim Peters8485b562004-08-04 18:46:34 +0000301 ... another
302 ... example
303 ... '''
304 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000305 >>> parser = doctest.DocTestParser()
306 >>> test = parser.get_doctest(docstring, globs, 'some_test',
307 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000308 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000309 <DocTest some_test from some_file:20 (2 examples)>
310 >>> len(test.examples)
311 2
312 >>> e1, e2 = test.examples
313 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000314 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000315 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000316 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000317
318Source information (name, filename, and line number) is available as
319attributes on the doctest object:
320
321 >>> (test.name, test.filename, test.lineno)
322 ('some_test', 'some_file', 20)
323
324The line number of an example within its containing file is found by
325adding the line number of the example and the line number of its
326containing test:
327
328 >>> test.lineno + e1.lineno
329 21
330 >>> test.lineno + e2.lineno
331 26
332
Martin Panter46f50722016-05-26 05:35:26 +0000333If the docstring contains inconsistent leading whitespace in the
Tim Peters8485b562004-08-04 18:46:34 +0000334expected output of an example, then `DocTest` will raise a ValueError:
335
336 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000337 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000338 ... bad
339 ... indentation
340 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000341 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000342 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000343 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000344
345If the docstring contains inconsistent leading whitespace on
346continuation lines, then `DocTest` will raise a ValueError:
347
348 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000349 ... >>> print(('bad indentation',
350 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000351 ... ('bad', 'indentation')
352 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000353 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000354 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000355 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000356
357If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
358will raise a ValueError:
359
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000360 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000361 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000362 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000363 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000364
365If there's no blank space after a PS2 prompt ('...'), then `DocTest`
366will raise a ValueError:
367
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000368 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000369 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000370 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000371 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000372
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100373Compare `DocTest`:
374
375 >>> docstring = '''
376 ... >>> print 12
377 ... 12
378 ... '''
379 >>> test = parser.get_doctest(docstring, globs, 'some_test',
380 ... 'some_test', 20)
381 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
382 ... 'some_test', 20)
383 >>> test == same_test
384 True
385 >>> test != same_test
386 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100387 >>> hash(test) == hash(same_test)
388 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100389 >>> docstring = '''
390 ... >>> print 42
391 ... 42
392 ... '''
393 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
394 ... 'other_file', 10)
395 >>> test == other_test
396 False
397 >>> test != other_test
398 True
399
400Compare `DocTestCase`:
401
402 >>> DocTestCase = doctest.DocTestCase
403 >>> test_case = DocTestCase(test)
404 >>> same_test_case = DocTestCase(same_test)
405 >>> other_test_case = DocTestCase(other_test)
406 >>> test_case == same_test_case
407 True
408 >>> test_case != same_test_case
409 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100410 >>> hash(test_case) == hash(same_test_case)
411 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100412 >>> test == other_test_case
413 False
414 >>> test != other_test_case
415 True
416
Tim Peters8485b562004-08-04 18:46:34 +0000417"""
418
Zachary Ware7119b452013-11-24 02:21:57 -0600419class test_DocTestFinder:
420 def basics(): r"""
Tim Peters8485b562004-08-04 18:46:34 +0000421Unit tests for the `DocTestFinder` class.
422
423DocTestFinder is used to extract DocTests from an object's docstring
424and the docstrings of its contained objects. It can be used with
425modules, functions, classes, methods, staticmethods, classmethods, and
426properties.
427
428Finding Tests in Functions
429~~~~~~~~~~~~~~~~~~~~~~~~~~
430For a function whose docstring contains examples, DocTestFinder.find()
431will return a single test (for that function's docstring):
432
Tim Peters8485b562004-08-04 18:46:34 +0000433 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000434
435We'll simulate a __file__ attr that ends in pyc:
436
437 >>> import test.test_doctest
438 >>> old = test.test_doctest.__file__
439 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
440
Tim Peters8485b562004-08-04 18:46:34 +0000441 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000442
Guido van Rossum7131f842007-02-09 20:13:25 +0000443 >>> print(tests) # doctest: +ELLIPSIS
Peter Donise0b81012020-03-26 11:53:16 -0400444 [<DocTest sample_func from ...:25 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000445
Tim Peters4de7c5c2004-08-23 22:38:05 +0000446The exact name depends on how test_doctest was invoked, so allow for
447leading path components.
448
449 >>> tests[0].filename # doctest: +ELLIPSIS
450 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000451
452 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000453
Jim Fulton07a349c2004-08-22 14:10:00 +0000454
Tim Peters8485b562004-08-04 18:46:34 +0000455 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000456 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000457 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000458
Edward Loper32ddbf72004-09-13 05:47:24 +0000459By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000460
461 >>> def no_docstring(v):
462 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000463 >>> finder.find(no_docstring)
464 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000465
466However, the optional argument `exclude_empty` to the DocTestFinder
467constructor can be used to exclude tests for objects with empty
468docstrings:
469
470 >>> def no_docstring(v):
471 ... pass
472 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
473 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000474 []
475
476If the function has a docstring with no examples, then a test with no
477examples is returned. (This lets `DocTestRunner` collect statistics
478about which functions have no tests -- but is that useful? And should
479an empty test also be created when there's no docstring?)
480
481 >>> def no_examples(v):
482 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000483 >>> finder.find(no_examples) # doctest: +ELLIPSIS
484 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000485
486Finding Tests in Classes
487~~~~~~~~~~~~~~~~~~~~~~~~
488For a class, DocTestFinder will create a test for the class's
489docstring, and will recursively explore its contents, including
490methods, classmethods, staticmethods, properties, and nested classes.
491
492 >>> finder = doctest.DocTestFinder()
493 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000494 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000495 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000496 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000497 3 SampleClass.NestedClass
498 1 SampleClass.NestedClass.__init__
499 1 SampleClass.__init__
500 2 SampleClass.a_classmethod
501 1 SampleClass.a_property
502 1 SampleClass.a_staticmethod
503 1 SampleClass.double
504 1 SampleClass.get
505
506New-style classes are also supported:
507
508 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000509 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000510 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000511 1 SampleNewStyleClass
512 1 SampleNewStyleClass.__init__
513 1 SampleNewStyleClass.double
514 1 SampleNewStyleClass.get
515
516Finding Tests in Modules
517~~~~~~~~~~~~~~~~~~~~~~~~
518For a module, DocTestFinder will create a test for the class's
519docstring, and will recursively explore its contents, including
520functions, classes, and the `__test__` dictionary, if it exists:
521
522 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000523 >>> import types
524 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000525 >>> def triple(val):
526 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000527 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000528 ... 33
529 ... '''
530 ... return val*3
531 >>> m.__dict__.update({
532 ... 'sample_func': sample_func,
533 ... 'SampleClass': SampleClass,
534 ... '__doc__': '''
535 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000536 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000537 ... module
538 ... ''',
539 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000540 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000541 ... 'c': triple}})
542
543 >>> finder = doctest.DocTestFinder()
544 >>> # Use module=test.test_doctest, to prevent doctest from
545 >>> # ignoring the objects since they weren't defined in m.
546 >>> import test.test_doctest
547 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000548 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000549 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000550 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000551 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000552 3 some_module.SampleClass.NestedClass
553 1 some_module.SampleClass.NestedClass.__init__
554 1 some_module.SampleClass.__init__
555 2 some_module.SampleClass.a_classmethod
556 1 some_module.SampleClass.a_property
557 1 some_module.SampleClass.a_staticmethod
558 1 some_module.SampleClass.double
559 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000560 1 some_module.__test__.c
561 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000562 1 some_module.sample_func
563
564Duplicate Removal
565~~~~~~~~~~~~~~~~~
566If a single object is listed twice (under different names), then tests
567will only be generated for it once:
568
Tim Petersf3f57472004-08-08 06:11:48 +0000569 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000570 >>> assert doctest_aliases.TwoNames.f
571 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000572 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000573 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000574 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000575 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000576 test.doctest_aliases.TwoNames
577
578 TwoNames.f and TwoNames.g are bound to the same object.
579 We can't guess which will be found in doctest's traversal of
580 TwoNames.__dict__ first, so we have to allow for either.
581
582 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000583 True
584
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000585Empty Tests
586~~~~~~~~~~~
587By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000588
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000589 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000590 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000591 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000592 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000593 3 SampleClass.NestedClass
594 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000595 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000596 2 SampleClass.a_classmethod
597 1 SampleClass.a_property
598 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000599 1 SampleClass.double
600 1 SampleClass.get
601
602By default, that excluded objects with no doctests. exclude_empty=False
603tells it to include (empty) tests for objects with no doctests. This feature
604is really to support backward compatibility in what doctest.master.summarize()
605displays.
606
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000607 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000608 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000609 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000610 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000611 3 SampleClass.NestedClass
612 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000613 0 SampleClass.NestedClass.get
614 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000615 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000616 2 SampleClass.a_classmethod
617 1 SampleClass.a_property
618 1 SampleClass.a_staticmethod
619 1 SampleClass.double
620 1 SampleClass.get
621
Tim Peters8485b562004-08-04 18:46:34 +0000622Turning off Recursion
623~~~~~~~~~~~~~~~~~~~~~
624DocTestFinder can be told not to look for tests in contained objects
625using the `recurse` flag:
626
627 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000628 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000629 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000630 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000631
632Line numbers
633~~~~~~~~~~~~
634DocTestFinder finds the line number of each example:
635
636 >>> def f(x):
637 ... '''
638 ... >>> x = 12
639 ...
640 ... some text
641 ...
642 ... >>> # examples are not created for comments & bare prompts.
643 ... >>>
644 ... ...
645 ...
646 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000647 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000648 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000649 ... >>> x//2
650 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000651 ... '''
652 >>> test = doctest.DocTestFinder().find(f)[0]
653 >>> [e.lineno for e in test.examples]
654 [1, 9, 12]
Zachary Ware7119b452013-11-24 02:21:57 -0600655"""
656
657 if int.__doc__: # simple check for --without-doc-strings, skip if lacking
658 def non_Python_modules(): r"""
Zachary Warea4b7a752013-11-24 01:19:09 -0600659
660Finding Doctests in Modules Not Written in Python
661~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
662DocTestFinder can also find doctests in most modules not written in Python.
663We'll use builtins as an example, since it almost certainly isn't written in
664plain ol' Python and is guaranteed to be available.
665
666 >>> import builtins
667 >>> tests = doctest.DocTestFinder().find(builtins)
sweeneydea81849b2020-04-22 17:05:48 -0400668 >>> 816 < len(tests) < 836 # approximate number of objects with docstrings
Zachary Ware7119b452013-11-24 02:21:57 -0600669 True
Zachary Warea4b7a752013-11-24 01:19:09 -0600670 >>> real_tests = [t for t in tests if len(t.examples) > 0]
Zachary Ware7119b452013-11-24 02:21:57 -0600671 >>> len(real_tests) # objects that actually have doctests
Niklas Fiekas8bd216d2020-05-29 18:28:02 +0200672 14
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
Niklas Fiekas8bd216d2020-05-29 18:28:02 +0200685 2 builtins.int.bit_count
Zachary Warea4b7a752013-11-24 01:19:09 -0600686 2 builtins.int.bit_length
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700687 5 builtins.memoryview.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600688 1 builtins.oct
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -0700689 1 builtins.zip
Zachary Warea4b7a752013-11-24 01:19:09 -0600690
691Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
692'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
693and 'int' is a type.
Tim Peters8485b562004-08-04 18:46:34 +0000694"""
695
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500696
697class TestDocTestFinder(unittest.TestCase):
698
699 def test_empty_namespace_package(self):
700 pkg_name = 'doctest_empty_pkg'
Nick Coghland5d9e022018-03-25 23:03:10 +1000701 with tempfile.TemporaryDirectory() as parent_dir:
702 pkg_dir = os.path.join(parent_dir, pkg_name)
703 os.mkdir(pkg_dir)
704 sys.path.append(parent_dir)
705 try:
706 mod = importlib.import_module(pkg_name)
707 finally:
708 support.forget(pkg_name)
709 sys.path.pop()
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500710
Xtreak8289e272019-12-13 23:36:53 +0530711 include_empty_finder = doctest.DocTestFinder(exclude_empty=False)
712 exclude_empty_finder = doctest.DocTestFinder(exclude_empty=True)
713
714 self.assertEqual(len(include_empty_finder.find(mod)), 1)
715 self.assertEqual(len(exclude_empty_finder.find(mod)), 0)
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500716
Edward Loper00f8da72004-08-26 18:05:07 +0000717def test_DocTestParser(): r"""
718Unit tests for the `DocTestParser` class.
719
720DocTestParser is used to parse docstrings containing doctest examples.
721
722The `parse` method divides a docstring into examples and intervening
723text:
724
725 >>> s = '''
726 ... >>> x, y = 2, 3 # no output expected
727 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000728 ... ... print(x)
729 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000730 ... 2
731 ... 3
732 ...
733 ... Some text.
734 ... >>> x+y
735 ... 5
736 ... '''
737 >>> parser = doctest.DocTestParser()
738 >>> for piece in parser.parse(s):
739 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000740 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000741 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000742 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000743 Text: '\n'
744 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
745 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000746 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000747 Text: '\nSome text.\n'
748 Example: ('x+y\n', '5\n', 9)
749 Text: ''
750
751The `get_examples` method returns just the examples:
752
753 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000754 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000755 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000756 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000757 ('x+y\n', '5\n', 9)
758
759The `get_doctest` method creates a Test from the examples, along with the
760given arguments:
761
762 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
763 >>> (test.name, test.filename, test.lineno)
764 ('name', 'filename', 5)
765 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000766 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000767 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000768 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000769 ('x+y\n', '5\n', 9)
770"""
771
Tim Peters8485b562004-08-04 18:46:34 +0000772class test_DocTestRunner:
773 def basics(): r"""
774Unit tests for the `DocTestRunner` class.
775
776DocTestRunner is used to run DocTest test cases, and to accumulate
777statistics. Here's a simple DocTest case we can use:
778
779 >>> def f(x):
780 ... '''
781 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000782 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000783 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000784 ... >>> x//2
785 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000786 ... '''
787 >>> test = doctest.DocTestFinder().find(f)[0]
788
789The main DocTestRunner interface is the `run` method, which runs a
790given DocTest case in a given namespace (globs). It returns a tuple
791`(f,t)`, where `f` is the number of failed tests and `t` is the number
792of tried tests.
793
794 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000795 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000796
797If any example produces incorrect output, then the test runner reports
798the failure and proceeds to the next example:
799
800 >>> def f(x):
801 ... '''
802 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000803 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000804 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000805 ... >>> x//2
806 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000807 ... '''
808 >>> test = doctest.DocTestFinder().find(f)[0]
809 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000810 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000811 Trying:
812 x = 12
813 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000814 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000815 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000816 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000817 Expecting:
818 14
Tim Peters8485b562004-08-04 18:46:34 +0000819 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000820 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000821 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000822 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000823 Expected:
824 14
825 Got:
826 12
Edward Loperaacf0832004-08-26 01:19:50 +0000827 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000828 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000829 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000830 6
Tim Peters8485b562004-08-04 18:46:34 +0000831 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000832 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000833"""
834 def verbose_flag(): r"""
835The `verbose` flag makes the test runner generate more detailed
836output:
837
838 >>> def f(x):
839 ... '''
840 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000841 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000842 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000843 ... >>> x//2
844 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000845 ... '''
846 >>> test = doctest.DocTestFinder().find(f)[0]
847
848 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000849 Trying:
850 x = 12
851 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000852 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000853 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000854 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000855 Expecting:
856 12
Tim Peters8485b562004-08-04 18:46:34 +0000857 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000858 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000859 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000860 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000861 6
Tim Peters8485b562004-08-04 18:46:34 +0000862 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000863 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000864
865If the `verbose` flag is unspecified, then the output will be verbose
866iff `-v` appears in sys.argv:
867
868 >>> # Save the real sys.argv list.
869 >>> old_argv = sys.argv
870
871 >>> # If -v does not appear in sys.argv, then output isn't verbose.
872 >>> sys.argv = ['test']
873 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000874 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000875
876 >>> # If -v does appear in sys.argv, then output is verbose.
877 >>> sys.argv = ['test', '-v']
878 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000879 Trying:
880 x = 12
881 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000882 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000883 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000884 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000885 Expecting:
886 12
Tim Peters8485b562004-08-04 18:46:34 +0000887 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000888 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000889 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000890 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000891 6
Tim Peters8485b562004-08-04 18:46:34 +0000892 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000893 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000894
895 >>> # Restore sys.argv
896 >>> sys.argv = old_argv
897
898In the remaining examples, the test runner's verbosity will be
899explicitly set, to ensure that the test behavior is consistent.
900 """
901 def exceptions(): r"""
902Tests of `DocTestRunner`'s exception handling.
903
904An expected exception is specified with a traceback message. The
905lines between the first line and the type/value may be omitted or
906replaced with any other string:
907
908 >>> def f(x):
909 ... '''
910 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000911 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000912 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000913 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000914 ... '''
915 >>> test = doctest.DocTestFinder().find(f)[0]
916 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000917 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000918
Edward Loper19b19582004-08-25 23:07:03 +0000919An example may not generate output before it raises an exception; if
920it does, then the traceback message will not be recognized as
921signaling an expected exception, so the example will be reported as an
922unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000923
924 >>> def f(x):
925 ... '''
926 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000927 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000928 ... pre-exception output
929 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000930 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000931 ... '''
932 >>> test = doctest.DocTestFinder().find(f)[0]
933 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000934 ... # doctest: +ELLIPSIS
935 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000936 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000937 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000938 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000939 Exception raised:
940 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000941 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000942 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000943
944Exception messages may contain newlines:
945
946 >>> def f(x):
947 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000948 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000949 ... Traceback (most recent call last):
950 ... ValueError: multi
951 ... line
952 ... message
953 ... '''
954 >>> test = doctest.DocTestFinder().find(f)[0]
955 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000956 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000957
958If an exception is expected, but an exception with the wrong type or
959message is raised, then it is reported as a failure:
960
961 >>> def f(x):
962 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000963 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000964 ... Traceback (most recent call last):
965 ... ValueError: wrong message
966 ... '''
967 >>> test = doctest.DocTestFinder().find(f)[0]
968 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000969 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000970 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000971 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000972 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000973 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000974 Expected:
975 Traceback (most recent call last):
976 ValueError: wrong message
977 Got:
978 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000979 ...
Tim Peters8485b562004-08-04 18:46:34 +0000980 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000981 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000982
Tim Peters1fbf9c52004-09-04 17:21:02 +0000983However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
984detail:
985
986 >>> def f(x):
987 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000988 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000989 ... Traceback (most recent call last):
990 ... ValueError: wrong message
991 ... '''
992 >>> test = doctest.DocTestFinder().find(f)[0]
993 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000994 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000995
Nick Coghlan5e76e942010-06-12 13:42:46 +0000996IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
997between Python versions. For example, in Python 2.x, the module path of
998the exception is not in the output, but this will fail under Python 3:
999
1000 >>> def f(x):
1001 ... r'''
1002 ... >>> from http.client import HTTPException
1003 ... >>> raise HTTPException('message')
1004 ... Traceback (most recent call last):
1005 ... HTTPException: message
1006 ... '''
1007 >>> test = doctest.DocTestFinder().find(f)[0]
1008 >>> doctest.DocTestRunner(verbose=False).run(test)
1009 ... # doctest: +ELLIPSIS
1010 **********************************************************************
1011 File ..., line 4, in f
1012 Failed example:
1013 raise HTTPException('message')
1014 Expected:
1015 Traceback (most recent call last):
1016 HTTPException: message
1017 Got:
1018 Traceback (most recent call last):
1019 ...
1020 http.client.HTTPException: message
1021 TestResults(failed=1, attempted=2)
1022
1023But in Python 3 the module path is included, and therefore a test must look
1024like the following test to succeed in Python 3. But that test will fail under
1025Python 2.
1026
1027 >>> def f(x):
1028 ... r'''
1029 ... >>> from http.client import HTTPException
1030 ... >>> raise HTTPException('message')
1031 ... Traceback (most recent call last):
1032 ... http.client.HTTPException: message
1033 ... '''
1034 >>> test = doctest.DocTestFinder().find(f)[0]
1035 >>> doctest.DocTestRunner(verbose=False).run(test)
1036 TestResults(failed=0, attempted=2)
1037
1038However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1039(or its unexpected absence) will be ignored:
1040
1041 >>> def f(x):
1042 ... r'''
1043 ... >>> from http.client import HTTPException
1044 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1045 ... Traceback (most recent call last):
1046 ... HTTPException: message
1047 ... '''
1048 >>> test = doctest.DocTestFinder().find(f)[0]
1049 >>> doctest.DocTestRunner(verbose=False).run(test)
1050 TestResults(failed=0, attempted=2)
1051
1052The module path will be completely ignored, so two different module paths will
1053still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1054be used when exceptions have changed module.
1055
1056 >>> def f(x):
1057 ... r'''
1058 ... >>> from http.client import HTTPException
1059 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1060 ... Traceback (most recent call last):
1061 ... foo.bar.HTTPException: message
1062 ... '''
1063 >>> test = doctest.DocTestFinder().find(f)[0]
1064 >>> doctest.DocTestRunner(verbose=False).run(test)
1065 TestResults(failed=0, attempted=2)
1066
Tim Peters1fbf9c52004-09-04 17:21:02 +00001067But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1068
1069 >>> def f(x):
1070 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001071 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001072 ... Traceback (most recent call last):
1073 ... TypeError: wrong type
1074 ... '''
1075 >>> test = doctest.DocTestFinder().find(f)[0]
1076 >>> doctest.DocTestRunner(verbose=False).run(test)
1077 ... # doctest: +ELLIPSIS
1078 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001079 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001080 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001081 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001082 Expected:
1083 Traceback (most recent call last):
1084 TypeError: wrong type
1085 Got:
1086 Traceback (most recent call last):
1087 ...
1088 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001089 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001090
Tim Petersf9a07f22013-12-03 21:02:05 -06001091If the exception does not have a message, you can still use
1092IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1093
1094 >>> def f(x):
1095 ... r'''
1096 ... >>> from http.client import HTTPException
1097 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1098 ... Traceback (most recent call last):
1099 ... foo.bar.HTTPException
1100 ... '''
1101 >>> test = doctest.DocTestFinder().find(f)[0]
1102 >>> doctest.DocTestRunner(verbose=False).run(test)
1103 TestResults(failed=0, attempted=2)
1104
1105Note that a trailing colon doesn't matter either:
1106
1107 >>> def f(x):
1108 ... r'''
1109 ... >>> from http.client import HTTPException
1110 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1111 ... Traceback (most recent call last):
1112 ... foo.bar.HTTPException:
1113 ... '''
1114 >>> test = doctest.DocTestFinder().find(f)[0]
1115 >>> doctest.DocTestRunner(verbose=False).run(test)
1116 TestResults(failed=0, attempted=2)
1117
Tim Peters8485b562004-08-04 18:46:34 +00001118If an exception is raised but not expected, then it is reported as an
1119unexpected exception:
1120
Tim Peters8485b562004-08-04 18:46:34 +00001121 >>> def f(x):
1122 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001123 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001124 ... 0
1125 ... '''
1126 >>> test = doctest.DocTestFinder().find(f)[0]
1127 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001128 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001129 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001130 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001131 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001132 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001133 Exception raised:
1134 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001135 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001136 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001137 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001138"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001139 def displayhook(): r"""
1140Test that changing sys.displayhook doesn't matter for doctest.
1141
1142 >>> import sys
1143 >>> orig_displayhook = sys.displayhook
1144 >>> def my_displayhook(x):
1145 ... print('hi!')
1146 >>> sys.displayhook = my_displayhook
1147 >>> def f():
1148 ... '''
1149 ... >>> 3
1150 ... 3
1151 ... '''
1152 >>> test = doctest.DocTestFinder().find(f)[0]
1153 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1154 >>> post_displayhook = sys.displayhook
1155
1156 We need to restore sys.displayhook now, so that we'll be able to test
1157 results.
1158
1159 >>> sys.displayhook = orig_displayhook
1160
1161 Ok, now we can check that everything is ok.
1162
1163 >>> r
1164 TestResults(failed=0, attempted=1)
1165 >>> post_displayhook is my_displayhook
1166 True
1167"""
Tim Peters8485b562004-08-04 18:46:34 +00001168 def optionflags(): r"""
1169Tests of `DocTestRunner`'s option flag handling.
1170
1171Several option flags can be used to customize the behavior of the test
1172runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001173to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001174together).
1175
1176The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1177and 1/0:
1178
1179 >>> def f(x):
1180 ... '>>> True\n1\n'
1181
1182 >>> # Without the flag:
1183 >>> test = doctest.DocTestFinder().find(f)[0]
1184 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001185 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001186
1187 >>> # With the flag:
1188 >>> test = doctest.DocTestFinder().find(f)[0]
1189 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1190 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001191 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001192 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001193 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001194 Failed example:
1195 True
1196 Expected:
1197 1
1198 Got:
1199 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001200 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001201
1202The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1203and the '<BLANKLINE>' marker:
1204
1205 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001206 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001207
1208 >>> # Without the flag:
1209 >>> test = doctest.DocTestFinder().find(f)[0]
1210 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001211 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001212
1213 >>> # With the flag:
1214 >>> test = doctest.DocTestFinder().find(f)[0]
1215 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1216 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001217 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001218 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001219 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001220 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001221 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001222 Expected:
1223 a
1224 <BLANKLINE>
1225 b
1226 Got:
1227 a
1228 <BLANKLINE>
1229 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001230 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001231
1232The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1233treated as equal:
1234
1235 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001236 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001237
1238 >>> # Without the flag:
1239 >>> test = doctest.DocTestFinder().find(f)[0]
1240 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001241 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001242 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001243 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001244 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001245 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001246 Expected:
1247 1 2
1248 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001249 Got:
1250 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001251 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001252
1253 >>> # With the flag:
1254 >>> test = doctest.DocTestFinder().find(f)[0]
1255 >>> flags = doctest.NORMALIZE_WHITESPACE
1256 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001257 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001258
Tim Peters026f8dc2004-08-19 16:38:58 +00001259 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001260 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001261 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1262 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1263
Tim Peters8485b562004-08-04 18:46:34 +00001264The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1265output to match any substring in the actual output:
1266
1267 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001268 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001269
1270 >>> # Without the flag:
1271 >>> test = doctest.DocTestFinder().find(f)[0]
1272 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001273 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001274 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001275 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001276 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001277 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001278 Expected:
1279 [0, 1, 2, ..., 14]
1280 Got:
1281 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001282 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001283
1284 >>> # With the flag:
1285 >>> test = doctest.DocTestFinder().find(f)[0]
1286 >>> flags = doctest.ELLIPSIS
1287 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001288 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001289
Tim Peterse594bee2004-08-22 01:47:51 +00001290 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001291
Guido van Rossume0192e52007-02-09 23:39:59 +00001292 >>> if 1:
1293 ... for i in range(100):
1294 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1295 ... print('!')
1296 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001297
Tim Peters026f8dc2004-08-19 16:38:58 +00001298 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001299
Guido van Rossume0192e52007-02-09 23:39:59 +00001300 >>> if 1: #doctest: +ELLIPSIS
1301 ... for i in range(20):
1302 ... print(i, end=' ')
1303 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001304 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001305
Tim Peters026f8dc2004-08-19 16:38:58 +00001306 Examples from the docs:
1307
Guido van Rossum805365e2007-05-07 22:24:25 +00001308 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001309 [0, 1, ..., 18, 19]
1310
Guido van Rossum805365e2007-05-07 22:24:25 +00001311 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001312 ... # doctest: +NORMALIZE_WHITESPACE
1313 [0, 1, ..., 18, 19]
1314
Thomas Wouters477c8d52006-05-27 19:21:47 +00001315The SKIP flag causes an example to be skipped entirely. I.e., the
1316example is not run. It can be useful in contexts where doctest
1317examples serve as both documentation and test cases, and an example
1318should be included for documentation purposes, but should not be
1319checked (e.g., because its output is random, or depends on resources
1320which would be unavailable.) The SKIP flag can also be used for
1321'commenting out' broken examples.
1322
1323 >>> import unavailable_resource # doctest: +SKIP
1324 >>> unavailable_resource.do_something() # doctest: +SKIP
1325 >>> unavailable_resource.blow_up() # doctest: +SKIP
1326 Traceback (most recent call last):
1327 ...
1328 UncheckedBlowUpError: Nobody checks me.
1329
1330 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001331 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001332 0.721216923889
1333
Edward Loper71f55af2004-08-26 01:41:51 +00001334The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001335and actual outputs to be displayed using a unified diff:
1336
1337 >>> def f(x):
1338 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001339 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001340 ... a
1341 ... B
1342 ... c
1343 ... d
1344 ... f
1345 ... g
1346 ... h
1347 ... '''
1348
1349 >>> # Without the flag:
1350 >>> test = doctest.DocTestFinder().find(f)[0]
1351 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001352 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001353 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001354 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001355 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001356 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001357 Expected:
1358 a
1359 B
1360 c
1361 d
1362 f
1363 g
1364 h
1365 Got:
1366 a
1367 b
1368 c
1369 d
1370 e
1371 f
1372 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001373 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001374
1375 >>> # With the flag:
1376 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001377 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001378 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001379 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001380 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001381 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001382 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001383 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001384 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001385 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001386 a
1387 -B
1388 +b
1389 c
1390 d
1391 +e
1392 f
1393 g
1394 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001395 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001396
Edward Loper71f55af2004-08-26 01:41:51 +00001397The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001398and actual outputs to be displayed using a context diff:
1399
Edward Loper71f55af2004-08-26 01:41:51 +00001400 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001401 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001402 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001403 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001404 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001405 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001406 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001407 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001408 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001409 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001410 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001411 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001412 a
1413 ! B
1414 c
1415 d
1416 f
1417 g
1418 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001419 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001420 a
1421 ! b
1422 c
1423 d
1424 + e
1425 f
1426 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001427 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001428
1429
Edward Loper71f55af2004-08-26 01:41:51 +00001430The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001431used by the popular ndiff.py utility. This does intraline difference
1432marking, as well as interline differences.
1433
1434 >>> def f(x):
1435 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001436 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001437 ... a b c d e f g h i j k 1 m
1438 ... '''
1439 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001440 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001441 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001442 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001443 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001444 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001445 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001446 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001447 Differences (ndiff with -expected +actual):
1448 - a b c d e f g h i j k 1 m
1449 ? ^
1450 + a b c d e f g h i j k l m
1451 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001452 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001453
Ezio Melotti13925002011-03-16 11:05:33 +02001454The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001455failing example:
1456
1457 >>> def f(x):
1458 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001459 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001460 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001461 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001462 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001463 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001464 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001465 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001466 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001467 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001468 ... 500
1469 ... '''
1470 >>> test = doctest.DocTestFinder().find(f)[0]
1471 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1472 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001473 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001474 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001475 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001476 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001477 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001478 Expected:
1479 200
1480 Got:
1481 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001482 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001483
Ezio Melotti13925002011-03-16 11:05:33 +02001484However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001485
1486 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001487 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001488 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001489 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001490 Expecting:
1491 1
1492 ok
1493 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001494 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001495 Expecting:
1496 200
1497 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001498 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001499 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001500 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001501 Expected:
1502 200
1503 Got:
1504 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001505 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001506
R David Murray5a9d7062012-11-21 15:09:21 -05001507The FAIL_FAST flag causes the runner to exit after the first failing example,
1508so subsequent examples are not even attempted:
1509
1510 >>> flags = doctest.FAIL_FAST
1511 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1512 ... # doctest: +ELLIPSIS
1513 **********************************************************************
1514 File ..., line 5, in f
1515 Failed example:
1516 print(2) # first failure
1517 Expected:
1518 200
1519 Got:
1520 2
1521 TestResults(failed=1, attempted=2)
1522
1523Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1524FAIL_FAST only:
1525
1526 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1527 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1528 ... # doctest: +ELLIPSIS
1529 **********************************************************************
1530 File ..., line 5, in f
1531 Failed example:
1532 print(2) # first failure
1533 Expected:
1534 200
1535 Got:
1536 2
1537 TestResults(failed=1, attempted=2)
1538
1539For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1540exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001541
1542 >>> def f(x):
1543 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001544 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001545 ... 1
1546 ... >>> raise ValueError(2) # first failure
1547 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001548 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001549 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001550 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001551 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001552 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001553 ... 500
1554 ... '''
1555 >>> test = doctest.DocTestFinder().find(f)[0]
1556 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1557 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1558 ... # doctest: +ELLIPSIS
1559 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001560 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001561 Failed example:
1562 raise ValueError(2) # first failure
1563 Exception raised:
1564 ...
1565 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001566 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001567 >>> flags = doctest.FAIL_FAST
1568 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1569 ... # doctest: +ELLIPSIS
1570 **********************************************************************
1571 File ..., line 5, in f
1572 Failed example:
1573 raise ValueError(2) # first failure
1574 Exception raised:
1575 ...
1576 ValueError: 2
1577 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001578
Thomas Wouters477c8d52006-05-27 19:21:47 +00001579New option flags can also be registered, via register_optionflag(). Here
1580we reach into doctest's internals a bit.
1581
1582 >>> unlikely = "UNLIKELY_OPTION_NAME"
1583 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1584 False
1585 >>> new_flag_value = doctest.register_optionflag(unlikely)
1586 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1587 True
1588
1589Before 2.4.4/2.5, registering a name more than once erroneously created
1590more than one flag value. Here we verify that's fixed:
1591
1592 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1593 >>> redundant_flag_value == new_flag_value
1594 True
1595
1596Clean up.
1597 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1598
Tim Petersc6cbab02004-08-22 19:43:28 +00001599 """
1600
Tim Peters8485b562004-08-04 18:46:34 +00001601 def option_directives(): r"""
1602Tests of `DocTestRunner`'s option directive mechanism.
1603
Edward Loper74bca7a2004-08-12 02:27:44 +00001604Option directives can be used to turn option flags on or off for a
1605single example. To turn an option on for an example, follow that
1606example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001607
1608 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001609 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001610 ... [0, 1, ..., 9]
1611 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001612 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001613 ... [0, 1, ..., 9]
1614 ... '''
1615 >>> test = doctest.DocTestFinder().find(f)[0]
1616 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001617 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001618 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001619 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001620 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001621 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001622 Expected:
1623 [0, 1, ..., 9]
1624 Got:
1625 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001626 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001627
1628To turn an option off for an example, follow that example with a
1629comment of the form ``# doctest: -OPTION``:
1630
1631 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001632 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001633 ... [0, 1, ..., 9]
1634 ...
1635 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001636 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001637 ... [0, 1, ..., 9]
1638 ... '''
1639 >>> test = doctest.DocTestFinder().find(f)[0]
1640 >>> doctest.DocTestRunner(verbose=False,
1641 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001642 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001643 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001644 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001645 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001646 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001647 Expected:
1648 [0, 1, ..., 9]
1649 Got:
1650 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001651 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001652
1653Option directives affect only the example that they appear with; they
1654do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001655
Edward Loper74bca7a2004-08-12 02:27:44 +00001656 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001657 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001658 ... [0, 1, ..., 9]
1659 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001660 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001661 ... [0, 1, ..., 9]
1662 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001663 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001664 ... [0, 1, ..., 9]
1665 ... '''
1666 >>> test = doctest.DocTestFinder().find(f)[0]
1667 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001668 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001669 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001670 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001671 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001672 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001673 Expected:
1674 [0, 1, ..., 9]
1675 Got:
1676 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001677 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001678 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001679 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001680 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001681 Expected:
1682 [0, 1, ..., 9]
1683 Got:
1684 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001685 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001686
Edward Loper74bca7a2004-08-12 02:27:44 +00001687Multiple options may be modified by a single option directive. They
1688may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001689
1690 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001691 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001692 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001693 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001694 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001695 ... [0, 1, ..., 9]
1696 ... '''
1697 >>> test = doctest.DocTestFinder().find(f)[0]
1698 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001699 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001700 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001701 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001702 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001703 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001704 Expected:
1705 [0, 1, ..., 9]
1706 Got:
1707 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001708 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001709
1710 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001711 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001712 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001713 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001714 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1715 ... [0, 1, ..., 9]
1716 ... '''
1717 >>> test = doctest.DocTestFinder().find(f)[0]
1718 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001719 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001720 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001721 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001722 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001723 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001724 Expected:
1725 [0, 1, ..., 9]
1726 Got:
1727 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001728 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001729
1730 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001731 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001732 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001733 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001734 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1735 ... [0, 1, ..., 9]
1736 ... '''
1737 >>> test = doctest.DocTestFinder().find(f)[0]
1738 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001739 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001740 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001741 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001742 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001743 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001744 Expected:
1745 [0, 1, ..., 9]
1746 Got:
1747 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001748 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001749
1750The option directive may be put on the line following the source, as
1751long as a continuation prompt is used:
1752
1753 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001754 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001755 ... ... # doctest: +ELLIPSIS
1756 ... [0, 1, ..., 9]
1757 ... '''
1758 >>> test = doctest.DocTestFinder().find(f)[0]
1759 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001760 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001761
Edward Loper74bca7a2004-08-12 02:27:44 +00001762For examples with multi-line source, the option directive may appear
1763at the end of any line:
1764
1765 >>> def f(x): r'''
1766 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001767 ... ... print(' ', x, end='', sep='')
1768 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001769 ...
1770 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001771 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1772 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001773 ... '''
1774 >>> test = doctest.DocTestFinder().find(f)[0]
1775 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001776 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001777
1778If more than one line of an example with multi-line source has an
1779option directive, then they are combined:
1780
1781 >>> def f(x): r'''
1782 ... Should fail (option directive not on the last line):
1783 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001784 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001785 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001786 ... '''
1787 >>> test = doctest.DocTestFinder().find(f)[0]
1788 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001789 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001790
1791It is an error to have a comment of the form ``# doctest:`` that is
1792*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1793``OPTION`` is an option that has been registered with
1794`register_option`:
1795
1796 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001797 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001798 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1799 Traceback (most recent call last):
1800 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1801
1802 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001803 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001804 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1805 Traceback (most recent call last):
1806 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1807
1808It is an error to use an option directive on a line that contains no
1809source:
1810
1811 >>> s = '>>> # doctest: +ELLIPSIS'
1812 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1813 Traceback (most recent call last):
1814 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 +00001815"""
1816
1817def test_testsource(): r"""
1818Unit tests for `testsource()`.
1819
1820The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001821test with that name in that module, and converts it to a script. The
1822example code is converted to regular Python code. The surrounding
1823words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001824
1825 >>> import test.test_doctest
1826 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001827 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001828 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001829 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001830 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001831 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001832 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001833 #
Edward Lopera5db6002004-08-12 02:41:30 +00001834 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001835 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001836
1837 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001838 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001839 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001840 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001841 ## 1
1842 ## 2
1843 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001844 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001845
1846 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001847 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001848 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001849 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001850 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001851 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001852 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001853 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001854 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001855"""
1856
1857def test_debug(): r"""
1858
1859Create a docstring that we want to debug:
1860
1861 >>> s = '''
1862 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001863 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001864 ... 12
1865 ... '''
1866
1867Create some fake stdin input, to feed to the debugger:
1868
Tim Peters8485b562004-08-04 18:46:34 +00001869 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001870 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001871
1872Run the debugger on the docstring, and then restore sys.stdin.
1873
Edward Loper2de91ba2004-08-27 02:07:46 +00001874 >>> try: doctest.debug_src(s)
1875 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001876 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001877 (Pdb) next
1878 12
Tim Peters8485b562004-08-04 18:46:34 +00001879 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001881 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001882 12
1883 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001884
1885"""
1886
Brett Cannon31f59292011-02-21 19:29:56 +00001887if not hasattr(sys, 'gettrace') or not sys.gettrace():
1888 def test_pdb_set_trace():
1889 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001890
Brett Cannon31f59292011-02-21 19:29:56 +00001891 You can use pdb.set_trace from a doctest. To do so, you must
1892 retrieve the set_trace function from the pdb module at the time
1893 you use it. The doctest module changes sys.stdout so that it can
1894 capture program output. It also temporarily replaces pdb.set_trace
1895 with a version that restores stdout. This is necessary for you to
1896 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001897
Brett Cannon31f59292011-02-21 19:29:56 +00001898 >>> doc = '''
1899 ... >>> x = 42
1900 ... >>> raise Exception('clé')
1901 ... Traceback (most recent call last):
1902 ... Exception: clé
1903 ... >>> import pdb; pdb.set_trace()
1904 ... '''
1905 >>> parser = doctest.DocTestParser()
1906 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1907 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001908
Brett Cannon31f59292011-02-21 19:29:56 +00001909 To demonstrate this, we'll create a fake standard input that
1910 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001911
Brett Cannon31f59292011-02-21 19:29:56 +00001912 >>> real_stdin = sys.stdin
1913 >>> sys.stdin = _FakeInput([
1914 ... 'print(x)', # print data defined by the example
1915 ... 'continue', # stop debugging
1916 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001917
Brett Cannon31f59292011-02-21 19:29:56 +00001918 >>> try: runner.run(test)
1919 ... finally: sys.stdin = real_stdin
1920 --Return--
1921 > <doctest foo-bar@baz[2]>(1)<module>()->None
1922 -> import pdb; pdb.set_trace()
1923 (Pdb) print(x)
1924 42
1925 (Pdb) continue
1926 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001927
Brett Cannon31f59292011-02-21 19:29:56 +00001928 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001929
Brett Cannon31f59292011-02-21 19:29:56 +00001930 >>> def calls_set_trace():
1931 ... y=2
1932 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001933
Brett Cannon31f59292011-02-21 19:29:56 +00001934 >>> doc = '''
1935 ... >>> x=1
1936 ... >>> calls_set_trace()
1937 ... '''
1938 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1939 >>> real_stdin = sys.stdin
1940 >>> sys.stdin = _FakeInput([
1941 ... 'print(y)', # print data defined in the function
1942 ... 'up', # out of function
1943 ... 'print(x)', # print data defined by the example
1944 ... 'continue', # stop debugging
1945 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001946
Brett Cannon31f59292011-02-21 19:29:56 +00001947 >>> try:
1948 ... runner.run(test)
1949 ... finally:
1950 ... sys.stdin = real_stdin
1951 --Return--
Serhiy Storchakae437a102016-04-24 21:41:02 +03001952 > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
Brett Cannon31f59292011-02-21 19:29:56 +00001953 -> import pdb; pdb.set_trace()
1954 (Pdb) print(y)
1955 2
1956 (Pdb) up
1957 > <doctest foo-bar@baz[1]>(1)<module>()
1958 -> calls_set_trace()
1959 (Pdb) print(x)
1960 1
1961 (Pdb) continue
1962 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001963
Brett Cannon31f59292011-02-21 19:29:56 +00001964 During interactive debugging, source code is shown, even for
1965 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001966
Brett Cannon31f59292011-02-21 19:29:56 +00001967 >>> doc = '''
1968 ... >>> def f(x):
1969 ... ... g(x*2)
1970 ... >>> def g(x):
1971 ... ... print(x+3)
1972 ... ... import pdb; pdb.set_trace()
1973 ... >>> f(3)
1974 ... '''
1975 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1976 >>> real_stdin = sys.stdin
1977 >>> sys.stdin = _FakeInput([
1978 ... 'list', # list source from example 2
1979 ... 'next', # return from g()
1980 ... 'list', # list source from example 1
1981 ... 'next', # return from f()
1982 ... 'list', # list source from example 3
1983 ... 'continue', # stop debugging
1984 ... ''])
1985 >>> try: runner.run(test)
1986 ... finally: sys.stdin = real_stdin
1987 ... # doctest: +NORMALIZE_WHITESPACE
1988 --Return--
1989 > <doctest foo-bar@baz[1]>(3)g()->None
1990 -> import pdb; pdb.set_trace()
1991 (Pdb) list
1992 1 def g(x):
1993 2 print(x+3)
1994 3 -> import pdb; pdb.set_trace()
1995 [EOF]
1996 (Pdb) next
1997 --Return--
1998 > <doctest foo-bar@baz[0]>(2)f()->None
1999 -> g(x*2)
2000 (Pdb) list
2001 1 def f(x):
2002 2 -> g(x*2)
2003 [EOF]
2004 (Pdb) next
2005 --Return--
2006 > <doctest foo-bar@baz[2]>(1)<module>()->None
2007 -> f(3)
2008 (Pdb) list
2009 1 -> f(3)
2010 [EOF]
2011 (Pdb) continue
2012 **********************************************************************
2013 File "foo-bar@baz.py", line 7, in foo-bar@baz
2014 Failed example:
2015 f(3)
2016 Expected nothing
2017 Got:
2018 9
2019 TestResults(failed=1, attempted=3)
2020 """
Jim Fulton356fd192004-08-09 11:34:47 +00002021
Brett Cannon31f59292011-02-21 19:29:56 +00002022 def test_pdb_set_trace_nested():
2023 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00002024
Brett Cannon31f59292011-02-21 19:29:56 +00002025 >>> class C(object):
2026 ... def calls_set_trace(self):
2027 ... y = 1
2028 ... import pdb; pdb.set_trace()
2029 ... self.f1()
2030 ... y = 2
2031 ... def f1(self):
2032 ... x = 1
2033 ... self.f2()
2034 ... x = 2
2035 ... def f2(self):
2036 ... z = 1
2037 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002038
Brett Cannon31f59292011-02-21 19:29:56 +00002039 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002040
Brett Cannon31f59292011-02-21 19:29:56 +00002041 >>> doc = '''
2042 ... >>> a = 1
2043 ... >>> calls_set_trace()
2044 ... '''
2045 >>> parser = doctest.DocTestParser()
2046 >>> runner = doctest.DocTestRunner(verbose=False)
2047 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2048 >>> real_stdin = sys.stdin
2049 >>> sys.stdin = _FakeInput([
2050 ... 'print(y)', # print data defined in the function
2051 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2052 ... 'up', 'print(x)',
2053 ... 'up', 'print(y)',
2054 ... 'up', 'print(foo)',
2055 ... 'continue', # stop debugging
2056 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002057
Brett Cannon31f59292011-02-21 19:29:56 +00002058 >>> try:
2059 ... runner.run(test)
2060 ... finally:
2061 ... sys.stdin = real_stdin
2062 ... # doctest: +REPORT_NDIFF
2063 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2064 -> self.f1()
2065 (Pdb) print(y)
2066 1
2067 (Pdb) step
2068 --Call--
2069 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2070 -> def f1(self):
2071 (Pdb) step
2072 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2073 -> x = 1
2074 (Pdb) step
2075 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2076 -> self.f2()
2077 (Pdb) step
2078 --Call--
2079 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2080 -> def f2(self):
2081 (Pdb) step
2082 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2083 -> z = 1
2084 (Pdb) step
2085 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2086 -> z = 2
2087 (Pdb) print(z)
2088 1
2089 (Pdb) up
2090 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2091 -> self.f2()
2092 (Pdb) print(x)
2093 1
2094 (Pdb) up
2095 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2096 -> self.f1()
2097 (Pdb) print(y)
2098 1
2099 (Pdb) up
2100 > <doctest foo-bar@baz[1]>(1)<module>()
2101 -> calls_set_trace()
2102 (Pdb) print(foo)
2103 *** NameError: name 'foo' is not defined
2104 (Pdb) continue
2105 TestResults(failed=0, attempted=2)
2106 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002107
Tim Peters19397e52004-08-06 22:02:59 +00002108def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002109 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002110
2111 We create a Suite by providing a module. A module can be provided
2112 by passing a module object:
2113
2114 >>> import unittest
2115 >>> import test.sample_doctest
2116 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2117 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002118 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002119
2120 We can also supply the module by name:
2121
2122 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2123 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002124 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002125
R David Murray5abd76a2012-09-10 10:15:58 -04002126 The module need not contain any doctest examples:
2127
2128 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2129 >>> suite.run(unittest.TestResult())
2130 <unittest.result.TestResult run=0 errors=0 failures=0>
2131
R David Murray1976d9b2014-04-14 20:28:36 -04002132 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002133
R David Murray1976d9b2014-04-14 20:28:36 -04002134 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002135 >>> suite.run(unittest.TestResult())
2136 <unittest.result.TestResult run=0 errors=0 failures=0>
2137
Tim Peters19397e52004-08-06 22:02:59 +00002138 We can use the current module:
2139
2140 >>> suite = test.sample_doctest.test_suite()
2141 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002142 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002143
R David Murray1976d9b2014-04-14 20:28:36 -04002144 We can also provide a DocTestFinder:
2145
2146 >>> finder = doctest.DocTestFinder()
2147 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2148 ... test_finder=finder)
2149 >>> suite.run(unittest.TestResult())
2150 <unittest.result.TestResult run=9 errors=0 failures=4>
2151
2152 The DocTestFinder need not return any tests:
2153
2154 >>> finder = doctest.DocTestFinder()
2155 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2156 ... test_finder=finder)
2157 >>> suite.run(unittest.TestResult())
2158 <unittest.result.TestResult run=0 errors=0 failures=0>
2159
Tim Peters19397e52004-08-06 22:02:59 +00002160 We can supply global variables. If we pass globs, they will be
2161 used instead of the module globals. Here we'll pass an empty
2162 globals, triggering an extra error:
2163
2164 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2165 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002166 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002167
2168 Alternatively, we can provide extra globals. Here we'll make an
2169 error go away by providing an extra global variable:
2170
2171 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2172 ... extraglobs={'y': 1})
2173 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002174 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002175
2176 You can pass option flags. Here we'll cause an extra error
2177 by disabling the blank-line feature:
2178
2179 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002180 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002181 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002182 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002183
Tim Peters1e277ee2004-08-07 05:37:52 +00002184 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002185
Jim Fultonf54bad42004-08-28 14:57:56 +00002186 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002187 ... import test.test_doctest
2188 ... test.test_doctest.sillySetup = True
2189
Jim Fultonf54bad42004-08-28 14:57:56 +00002190 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002191 ... import test.test_doctest
2192 ... del test.test_doctest.sillySetup
2193
2194 Here, we installed a silly variable that the test expects:
2195
2196 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2197 ... setUp=setUp, tearDown=tearDown)
2198 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002199 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002200
2201 But the tearDown restores sanity:
2202
2203 >>> import test.test_doctest
2204 >>> test.test_doctest.sillySetup
2205 Traceback (most recent call last):
2206 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002207 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002208
Berker Peksag4882cac2015-04-14 09:30:01 +03002209 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002210 we'll use the setUp function to supply the missing variable y:
2211
2212 >>> def setUp(test):
2213 ... test.globs['y'] = 1
2214
2215 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2216 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002217 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002218
2219 Here, we didn't need to use a tearDown function because we
2220 modified the test globals, which are a copy of the
2221 sample_doctest module dictionary. The test globals are
2222 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002223 """
2224
2225def test_DocFileSuite():
2226 """We can test tests found in text files using a DocFileSuite.
2227
2228 We create a suite by providing the names of one or more text
2229 files that include examples:
2230
2231 >>> import unittest
2232 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002233 ... 'test_doctest2.txt',
2234 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002235 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002236 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002237
2238 The test files are looked for in the directory containing the
2239 calling module. A package keyword argument can be provided to
2240 specify a different relative location.
2241
2242 >>> import unittest
2243 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2244 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002245 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002246 ... package='test')
2247 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002248 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002249
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002250 Support for using a package's __loader__.get_data() is also
2251 provided.
2252
2253 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002254 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002255 >>> if not hasattr(test, '__loader__'):
2256 ... test.__loader__ = pkgutil.get_loader(test)
2257 ... added_loader = True
2258 >>> try:
2259 ... suite = doctest.DocFileSuite('test_doctest.txt',
2260 ... 'test_doctest2.txt',
2261 ... 'test_doctest4.txt',
2262 ... package='test')
2263 ... suite.run(unittest.TestResult())
2264 ... finally:
2265 ... if added_loader:
2266 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002267 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002268
Edward Loper0273f5b2004-09-18 20:27:04 +00002269 '/' should be used as a path separator. It will be converted
2270 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002271
2272 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2273 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002274 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002275
Edward Loper0273f5b2004-09-18 20:27:04 +00002276 If DocFileSuite is used from an interactive session, then files
2277 are resolved relative to the directory of sys.argv[0]:
2278
Christian Heimes45f9af32007-11-27 21:50:00 +00002279 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002280 >>> save_argv = sys.argv
2281 >>> sys.argv = [test.test_doctest.__file__]
2282 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002283 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002284 >>> sys.argv = save_argv
2285
Edward Loper052d0cd2004-09-19 17:19:33 +00002286 By setting `module_relative=False`, os-specific paths may be
2287 used (including absolute paths and paths relative to the
2288 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002289
2290 >>> # Get the absolute path of the test package.
2291 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2292 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2293
2294 >>> # Use it to find the absolute path of test_doctest.txt.
2295 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2296
Edward Loper052d0cd2004-09-19 17:19:33 +00002297 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002298 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002299 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002300
Edward Loper052d0cd2004-09-19 17:19:33 +00002301 It is an error to specify `package` when `module_relative=False`:
2302
2303 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2304 ... package='test')
2305 Traceback (most recent call last):
2306 ValueError: Package may only be specified for module-relative paths.
2307
Tim Peters19397e52004-08-06 22:02:59 +00002308 You can specify initial global variables:
2309
2310 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2311 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002312 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002313 ... globs={'favorite_color': 'blue'})
2314 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002315 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002316
2317 In this case, we supplied a missing favorite color. You can
2318 provide doctest options:
2319
2320 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2321 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002322 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002323 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2324 ... globs={'favorite_color': 'blue'})
2325 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002326 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002327
2328 And, you can provide setUp and tearDown functions:
2329
Jim Fultonf54bad42004-08-28 14:57:56 +00002330 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002331 ... import test.test_doctest
2332 ... test.test_doctest.sillySetup = True
2333
Jim Fultonf54bad42004-08-28 14:57:56 +00002334 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002335 ... import test.test_doctest
2336 ... del test.test_doctest.sillySetup
2337
2338 Here, we installed a silly variable that the test expects:
2339
2340 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2341 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002342 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002343 ... setUp=setUp, tearDown=tearDown)
2344 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002345 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002346
2347 But the tearDown restores sanity:
2348
2349 >>> import test.test_doctest
2350 >>> test.test_doctest.sillySetup
2351 Traceback (most recent call last):
2352 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002353 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002354
Berker Peksag4882cac2015-04-14 09:30:01 +03002355 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002356 Here, we'll use a setUp function to set the favorite color in
2357 test_doctest.txt:
2358
2359 >>> def setUp(test):
2360 ... test.globs['favorite_color'] = 'blue'
2361
2362 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2363 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002364 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002365
2366 Here, we didn't need to use a tearDown function because we
2367 modified the test globals. The test globals are
2368 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002369
Fred Drake7c404a42004-12-21 23:46:34 +00002370 Tests in a file run using `DocFileSuite` can also access the
2371 `__file__` global, which is set to the name of the file
2372 containing the tests:
2373
Benjamin Petersonab078e92016-07-13 21:13:29 -07002374 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
Fred Drake7c404a42004-12-21 23:46:34 +00002375 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002376 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002377
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002378 If the tests contain non-ASCII characters, we have to specify which
2379 encoding the file is encoded with. We do so by using the `encoding`
2380 parameter:
2381
2382 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2383 ... 'test_doctest2.txt',
2384 ... 'test_doctest4.txt',
2385 ... encoding='utf-8')
2386 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002387 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002388
Jim Fultonf54bad42004-08-28 14:57:56 +00002389 """
Tim Peters19397e52004-08-06 22:02:59 +00002390
Jim Fulton07a349c2004-08-22 14:10:00 +00002391def test_trailing_space_in_test():
2392 """
Tim Petersa7def722004-08-23 22:13:22 +00002393 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002394
Jim Fulton07a349c2004-08-22 14:10:00 +00002395 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002396 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002397 foo \n
2398 """
Tim Peters19397e52004-08-06 22:02:59 +00002399
Yury Selivanovb532df62014-12-08 15:00:05 -05002400class Wrapper:
2401 def __init__(self, func):
2402 self.func = func
2403 functools.update_wrapper(self, func)
2404
2405 def __call__(self, *args, **kwargs):
2406 self.func(*args, **kwargs)
2407
2408@Wrapper
2409def test_look_in_unwrapped():
2410 """
2411 Docstrings in wrapped functions must be detected as well.
2412
2413 >>> 'one other test'
2414 'one other test'
2415 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002416
2417def test_unittest_reportflags():
2418 """Default unittest reporting flags can be set to control reporting
2419
2420 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2421 only the first failure of each test. First, we'll look at the
2422 output without the flag. The file test_doctest.txt file has two
2423 tests. They both fail if blank lines are disabled:
2424
2425 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2426 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2427 >>> import unittest
2428 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002429 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002430 Traceback ...
2431 Failed example:
2432 favorite_color
2433 ...
2434 Failed example:
2435 if 1:
2436 ...
2437
2438 Note that we see both failures displayed.
2439
2440 >>> old = doctest.set_unittest_reportflags(
2441 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2442
2443 Now, when we run the test:
2444
2445 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002446 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002447 Traceback ...
2448 Failed example:
2449 favorite_color
2450 Exception raised:
2451 ...
2452 NameError: name 'favorite_color' is not defined
2453 <BLANKLINE>
2454 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002455
Jim Fultonf54bad42004-08-28 14:57:56 +00002456 We get only the first failure.
2457
2458 If we give any reporting options when we set up the tests,
2459 however:
2460
2461 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2462 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2463
2464 Then the default eporting options are ignored:
2465
2466 >>> result = suite.run(unittest.TestResult())
Pablo Galindoc5dc60e2019-01-10 14:29:40 +00002467
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302468 *NOTE*: These doctest are intentionally not placed in raw string to depict
2469 the trailing whitespace using `\x20` in the diff below.
2470
Guido van Rossum7131f842007-02-09 20:13:25 +00002471 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002472 Traceback ...
2473 Failed example:
2474 favorite_color
2475 ...
2476 Failed example:
2477 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002478 print('a')
2479 print()
2480 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002481 Differences (ndiff with -expected +actual):
2482 a
2483 - <BLANKLINE>
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302484 +\x20
Jim Fultonf54bad42004-08-28 14:57:56 +00002485 b
2486 <BLANKLINE>
2487 <BLANKLINE>
2488
2489
2490 Test runners can restore the formatting flags after they run:
2491
2492 >>> ignored = doctest.set_unittest_reportflags(old)
2493
2494 """
2495
Edward Loper052d0cd2004-09-19 17:19:33 +00002496def test_testfile(): r"""
2497Tests for the `testfile()` function. This function runs all the
Min ho Kimc4cacc82019-07-31 08:16:13 +10002498doctest examples in a given file. In its simple invocation, it is
Edward Loper052d0cd2004-09-19 17:19:33 +00002499called with the name of a file, which is taken to be relative to the
2500calling module. The return value is (#failures, #tests).
2501
Florent Xicluna59250852010-02-27 14:21:57 +00002502We don't want `-v` in sys.argv for these tests.
2503
2504 >>> save_argv = sys.argv
2505 >>> if '-v' in sys.argv:
2506 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2507
2508
Edward Loper052d0cd2004-09-19 17:19:33 +00002509 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2510 **********************************************************************
2511 File "...", line 6, in test_doctest.txt
2512 Failed example:
2513 favorite_color
2514 Exception raised:
2515 ...
2516 NameError: name 'favorite_color' is not defined
2517 **********************************************************************
2518 1 items had failures:
2519 1 of 2 in test_doctest.txt
2520 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002521 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002522 >>> doctest.master = None # Reset master.
2523
2524(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002525`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002526same name.)
2527
2528Globals may be specified with the `globs` and `extraglobs` parameters:
2529
2530 >>> globs = {'favorite_color': 'blue'}
2531 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002532 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002533 >>> doctest.master = None # Reset master.
2534
2535 >>> extraglobs = {'favorite_color': 'red'}
2536 >>> doctest.testfile('test_doctest.txt', globs=globs,
2537 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2538 **********************************************************************
2539 File "...", line 6, in test_doctest.txt
2540 Failed example:
2541 favorite_color
2542 Expected:
2543 'blue'
2544 Got:
2545 'red'
2546 **********************************************************************
2547 1 items had failures:
2548 1 of 2 in test_doctest.txt
2549 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002550 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002551 >>> doctest.master = None # Reset master.
2552
2553The file may be made relative to a given module or package, using the
2554optional `module_relative` parameter:
2555
2556 >>> doctest.testfile('test_doctest.txt', globs=globs,
2557 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002558 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002559 >>> doctest.master = None # Reset master.
2560
Ezio Melotti13925002011-03-16 11:05:33 +02002561Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002562
2563 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2564 Trying:
2565 favorite_color
2566 Expecting:
2567 'blue'
2568 ok
2569 Trying:
2570 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002571 print('a')
2572 print()
2573 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002574 Expecting:
2575 a
2576 <BLANKLINE>
2577 b
2578 ok
2579 1 items passed all tests:
2580 2 tests in test_doctest.txt
2581 2 tests in 1 items.
2582 2 passed and 0 failed.
2583 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002584 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002585 >>> doctest.master = None # Reset master.
2586
2587The name of the test may be specified with the optional `name`
2588parameter:
2589
2590 >>> doctest.testfile('test_doctest.txt', name='newname')
2591 ... # doctest: +ELLIPSIS
2592 **********************************************************************
2593 File "...", line 6, in newname
2594 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002595 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002596 >>> doctest.master = None # Reset master.
2597
Ezio Melotti13925002011-03-16 11:05:33 +02002598The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002599parameter:
2600
2601 >>> doctest.testfile('test_doctest.txt', report=False)
2602 ... # doctest: +ELLIPSIS
2603 **********************************************************************
2604 File "...", line 6, in test_doctest.txt
2605 Failed example:
2606 favorite_color
2607 Exception raised:
2608 ...
2609 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002610 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002611 >>> doctest.master = None # Reset master.
2612
2613The optional keyword argument `raise_on_error` can be used to raise an
2614exception on the first error (which may be useful for postmortem
2615debugging):
2616
2617 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2618 ... # doctest: +ELLIPSIS
2619 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002620 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002621 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002622
2623If the tests contain non-ASCII characters, the tests might fail, since
2624it's unknown which encoding is used. The encoding can be specified
2625using the optional keyword argument `encoding`:
2626
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002627 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002628 **********************************************************************
2629 File "...", line 7, in test_doctest4.txt
2630 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002631 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002632 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002633 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002634 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002635 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002636 **********************************************************************
2637 ...
2638 **********************************************************************
2639 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002640 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002641 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002642 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002643 >>> doctest.master = None # Reset master.
2644
2645 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002646 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002647 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002648
2649Test the verbose output:
2650
2651 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2652 Trying:
2653 'föö'
2654 Expecting:
2655 'f\xf6\xf6'
2656 ok
2657 Trying:
2658 'bÄ…r'
2659 Expecting:
2660 'b\u0105r'
2661 ok
2662 1 items passed all tests:
2663 2 tests in test_doctest4.txt
2664 2 tests in 1 items.
2665 2 passed and 0 failed.
2666 Test passed.
2667 TestResults(failed=0, attempted=2)
2668 >>> doctest.master = None # Reset master.
2669 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002670"""
2671
Peter Donise0b81012020-03-26 11:53:16 -04002672class TestImporter(importlib.abc.MetaPathFinder, importlib.abc.ResourceLoader):
2673
2674 def find_spec(self, fullname, path, target=None):
2675 return importlib.util.spec_from_file_location(fullname, path, loader=self)
2676
2677 def get_data(self, path):
2678 with open(path, mode='rb') as f:
2679 return f.read()
2680
2681class TestHook:
2682
2683 def __init__(self, pathdir):
2684 self.sys_path = sys.path[:]
2685 self.meta_path = sys.meta_path[:]
2686 self.path_hooks = sys.path_hooks[:]
2687 sys.path.append(pathdir)
2688 sys.path_importer_cache.clear()
2689 self.modules_before = sys.modules.copy()
2690 self.importer = TestImporter()
2691 sys.meta_path.append(self.importer)
2692
2693 def remove(self):
2694 sys.path[:] = self.sys_path
2695 sys.meta_path[:] = self.meta_path
2696 sys.path_hooks[:] = self.path_hooks
2697 sys.path_importer_cache.clear()
2698 sys.modules.clear()
2699 sys.modules.update(self.modules_before)
2700
2701
2702@contextlib.contextmanager
2703def test_hook(pathdir):
2704 hook = TestHook(pathdir)
2705 try:
2706 yield hook
2707 finally:
2708 hook.remove()
2709
2710
R David Murrayb48cb292014-10-02 22:42:42 -04002711def test_lineendings(): r"""
Peter Donise0b81012020-03-26 11:53:16 -04002712*nix systems use \n line endings, while Windows systems use \r\n, and
2713old Mac systems used \r, which Python still recognizes as a line ending. Python
R David Murrayb48cb292014-10-02 22:42:42 -04002714handles this using universal newline mode for reading files. Let's make
2715sure doctest does so (issue 8473) by creating temporary test files using each
Peter Donise0b81012020-03-26 11:53:16 -04002716of the three line disciplines. At least one will not match either the universal
2717newline \n or os.linesep for the platform the test is run on.
R David Murrayb48cb292014-10-02 22:42:42 -04002718
2719Windows line endings first:
2720
2721 >>> import tempfile, os
2722 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002723 >>> with open(fn, 'wb') as f:
2724 ... 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 -04002725 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002726 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002727 TestResults(failed=0, attempted=1)
2728 >>> os.remove(fn)
2729
2730And now *nix line endings:
2731
2732 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002733 >>> with open(fn, 'wb') as f:
2734 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002735 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002736 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002737 TestResults(failed=0, attempted=1)
2738 >>> os.remove(fn)
2739
Peter Donise0b81012020-03-26 11:53:16 -04002740And finally old Mac line endings:
2741
2742 >>> fn = tempfile.mktemp()
2743 >>> with open(fn, 'wb') as f:
2744 ... f.write(b'Test:\r\r >>> x = 1 + 1\r\rDone.\r')
2745 30
2746 >>> doctest.testfile(fn, module_relative=False, verbose=False)
2747 TestResults(failed=0, attempted=1)
2748 >>> os.remove(fn)
2749
2750Now we test with a package loader that has a get_data method, since that
2751bypasses the standard universal newline handling so doctest has to do the
2752newline conversion itself; let's make sure it does so correctly (issue 1812).
2753We'll write a file inside the package that has all three kinds of line endings
2754in it, and use a package hook to install a custom loader; on any platform,
2755at least one of the line endings will raise a ValueError for inconsistent
2756whitespace if doctest does not correctly do the newline conversion.
2757
2758 >>> dn = tempfile.mkdtemp()
2759 >>> pkg = os.path.join(dn, "doctest_testpkg")
2760 >>> os.mkdir(pkg)
2761 >>> support.create_empty_file(os.path.join(pkg, "__init__.py"))
2762 >>> fn = os.path.join(pkg, "doctest_testfile.txt")
2763 >>> with open(fn, 'wb') as f:
2764 ... f.write(
2765 ... b'Test:\r\n\r\n'
2766 ... b' >>> x = 1 + 1\r\n\r\n'
2767 ... b'Done.\r\n'
2768 ... b'Test:\n\n'
2769 ... b' >>> x = 1 + 1\n\n'
2770 ... b'Done.\n'
2771 ... b'Test:\r\r'
2772 ... b' >>> x = 1 + 1\r\r'
2773 ... b'Done.\r'
2774 ... )
2775 95
2776 >>> with test_hook(dn):
2777 ... doctest.testfile("doctest_testfile.txt", package="doctest_testpkg", verbose=False)
2778 TestResults(failed=0, attempted=3)
2779 >>> shutil.rmtree(dn)
2780
R David Murrayb48cb292014-10-02 22:42:42 -04002781"""
2782
R. David Murray58641de2009-06-12 15:33:19 +00002783def test_testmod(): r"""
2784Tests for the testmod function. More might be useful, but for now we're just
2785testing the case raised by Issue 6195, where trying to doctest a C module would
2786fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2787out of the binary module.
2788
2789 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002790 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002791 TestResults(failed=0, attempted=0)
2792"""
2793
Victor Stinner9d396392010-10-16 21:54:59 +00002794try:
2795 os.fsencode("foo-bär@baz.py")
2796except UnicodeEncodeError:
2797 # Skip the test: the filesystem encoding is unable to encode the filename
2798 pass
2799else:
2800 def test_unicode(): """
2801Check doctest with a non-ascii filename:
2802
2803 >>> doc = '''
2804 ... >>> raise Exception('clé')
2805 ... '''
2806 ...
2807 >>> parser = doctest.DocTestParser()
2808 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2809 >>> test
2810 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2811 >>> runner = doctest.DocTestRunner(verbose=False)
2812 >>> runner.run(test) # doctest: +ELLIPSIS
2813 **********************************************************************
2814 File "foo-bär@baz.py", line 2, in foo-bär@baz
2815 Failed example:
2816 raise Exception('clé')
2817 Exception raised:
2818 Traceback (most recent call last):
2819 File ...
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03002820 exec(compile(example.source, filename, "single",
Victor Stinner9d396392010-10-16 21:54:59 +00002821 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2822 raise Exception('clé')
2823 Exception: clé
2824 TestResults(failed=1, attempted=1)
2825 """
2826
R David Murray5707d502013-06-23 14:24:13 -04002827def test_CLI(): r"""
2828The doctest module can be used to run doctests against an arbitrary file.
2829These tests test this CLI functionality.
2830
2831We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002832to a temp dir to run the command against. Due to a current limitation in
2833script_helpers, though, we need a little utility function to turn the returned
2834output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002835
R David Murray4af68982013-06-25 08:11:22 -04002836 >>> def normalize(s):
2837 ... return '\n'.join(s.decode().splitlines())
2838
R David Murray4af68982013-06-25 08:11:22 -04002839With those preliminaries out of the way, we'll start with a file with two
2840simple tests and no errors. We'll run both the unadorned doctest command, and
2841the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002842
Berker Peksagce643912015-05-06 06:33:17 +03002843 >>> from test.support import script_helper, temp_dir
2844 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002845 ... fn = os.path.join(tmpdir, 'myfile.doc')
2846 ... with open(fn, 'w') as f:
2847 ... _ = f.write('This is a very simple test file.\n')
2848 ... _ = f.write(' >>> 1 + 1\n')
2849 ... _ = f.write(' 2\n')
2850 ... _ = f.write(' >>> "a"\n')
2851 ... _ = f.write(" 'a'\n")
2852 ... _ = f.write('\n')
2853 ... _ = f.write('And that is it.\n')
2854 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002855 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002856 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002857 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002858
2859With no arguments and passing tests, we should get no output:
2860
2861 >>> rc1, out1, err1
2862 (0, b'', b'')
2863
2864With the verbose flag, we should see the test output, but no error output:
2865
2866 >>> rc2, err2
2867 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002868 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002869 Trying:
2870 1 + 1
2871 Expecting:
2872 2
2873 ok
2874 Trying:
2875 "a"
2876 Expecting:
2877 'a'
2878 ok
2879 1 items passed all tests:
2880 2 tests in myfile.doc
2881 2 tests in 1 items.
2882 2 passed and 0 failed.
2883 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002884
2885Now we'll write a couple files, one with three tests, the other a python module
2886with two tests, both of the files having "errors" in the tests that can be made
2887non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2888the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002889allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002890ability to process more than one file on the command line and, since the second
2891file ends in '.py', its handling of python module files (as opposed to straight
2892text files).
2893
Berker Peksagce643912015-05-06 06:33:17 +03002894 >>> from test.support import script_helper, temp_dir
2895 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002896 ... fn = os.path.join(tmpdir, 'myfile.doc')
2897 ... with open(fn, 'w') as f:
2898 ... _ = f.write('This is another simple test file.\n')
2899 ... _ = f.write(' >>> 1 + 1\n')
2900 ... _ = f.write(' 2\n')
2901 ... _ = f.write(' >>> "abcdef"\n')
2902 ... _ = f.write(" 'a...f'\n")
2903 ... _ = f.write(' >>> "ajkml"\n')
2904 ... _ = f.write(" 'a...l'\n")
2905 ... _ = f.write('\n')
2906 ... _ = f.write('And that is it.\n')
2907 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2908 ... with open(fn2, 'w') as f:
2909 ... _ = f.write('def test_func():\n')
2910 ... _ = f.write(' \"\"\"\n')
2911 ... _ = f.write(' This is simple python test function.\n')
2912 ... _ = f.write(' >>> 1 + 1\n')
2913 ... _ = f.write(' 2\n')
2914 ... _ = f.write(' >>> "abc def"\n')
2915 ... _ = f.write(" 'abc def'\n")
2916 ... _ = f.write("\n")
2917 ... _ = f.write(' \"\"\"\n')
R David Murray5707d502013-06-23 14:24:13 -04002918 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002919 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002920 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002921 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002922 ... rc3, out3, err3 = script_helper.assert_python_ok(
2923 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002924 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002925 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002926 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002927 ... rc5, out5, err5 = script_helper.assert_python_ok(
2928 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002929 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002930
2931Our first test run will show the errors from the first file (doctest stops if a
2932file has errors). Note that doctest test-run error output appears on stdout,
2933not stderr:
2934
2935 >>> rc1, err1
2936 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002937 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002938 **********************************************************************
2939 File "...myfile.doc", line 4, in myfile.doc
2940 Failed example:
2941 "abcdef"
2942 Expected:
2943 'a...f'
2944 Got:
2945 'abcdef'
2946 **********************************************************************
2947 File "...myfile.doc", line 6, in myfile.doc
2948 Failed example:
2949 "ajkml"
2950 Expected:
2951 'a...l'
2952 Got:
2953 'ajkml'
2954 **********************************************************************
2955 1 items had failures:
2956 2 of 3 in myfile.doc
2957 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002958
2959With -o ELLIPSIS specified, the second run, against just the first file, should
2960produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2961should the third, which ran against both files:
2962
2963 >>> rc2, out2, err2
2964 (0, b'', b'')
2965 >>> rc3, out3, err3
2966 (0, b'', b'')
2967
2968The fourth run uses FAIL_FAST, so we should see only one error:
2969
2970 >>> rc4, err4
2971 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002972 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002973 **********************************************************************
2974 File "...myfile.doc", line 4, in myfile.doc
2975 Failed example:
2976 "abcdef"
2977 Expected:
2978 'a...f'
2979 Got:
2980 'abcdef'
2981 **********************************************************************
2982 1 items had failures:
2983 1 of 2 in myfile.doc
2984 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002985
2986The fifth test uses verbose with the two options, so we should get verbose
2987success output for the tests in both files:
2988
2989 >>> rc5, err5
2990 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002991 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002992 Trying:
2993 1 + 1
2994 Expecting:
2995 2
2996 ok
2997 Trying:
2998 "abcdef"
2999 Expecting:
3000 'a...f'
3001 ok
3002 Trying:
3003 "ajkml"
3004 Expecting:
3005 'a...l'
3006 ok
3007 1 items passed all tests:
3008 3 tests in myfile.doc
3009 3 tests in 1 items.
3010 3 passed and 0 failed.
3011 Test passed.
3012 Trying:
3013 1 + 1
3014 Expecting:
3015 2
3016 ok
3017 Trying:
3018 "abc def"
3019 Expecting:
3020 'abc def'
3021 ok
3022 1 items had no tests:
3023 myfile2
3024 1 items passed all tests:
3025 2 tests in myfile2.test_func
3026 2 tests in 2 items.
3027 2 passed and 0 failed.
3028 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04003029
3030We should also check some typical error cases.
3031
3032Invalid file name:
3033
3034 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03003035 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04003036 >>> rc, out
3037 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04003038 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003039 Traceback (most recent call last):
3040 ...
3041 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
3042
3043Invalid doctest option:
3044
3045 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03003046 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04003047 >>> rc, out
3048 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04003049 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003050 usage...invalid...nosuchoption...
3051
3052"""
3053
Sanyam Khuranacbb16452019-01-09 19:08:38 +05303054def test_no_trailing_whitespace_stripping():
3055 r"""
3056 The fancy reports had a bug for a long time where any trailing whitespace on
3057 the reported diff lines was stripped, making it impossible to see the
3058 differences in line reported as different that differed only in the amount of
3059 trailing whitespace. The whitespace still isn't particularly visible unless
3060 you use NDIFF, but at least it is now there to be found.
3061
3062 *NOTE*: This snippet was intentionally put inside a raw string to get rid of
3063 leading whitespace error in executing the example below
3064
3065 >>> def f(x):
3066 ... r'''
3067 ... >>> print('\n'.join(['a ', 'b']))
3068 ... a
3069 ... b
3070 ... '''
3071 """
3072 """
3073 *NOTE*: These doctest are not placed in raw string to depict the trailing whitespace
3074 using `\x20`
3075
3076 >>> test = doctest.DocTestFinder().find(f)[0]
3077 >>> flags = doctest.REPORT_NDIFF
3078 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
3079 ... # doctest: +ELLIPSIS
3080 **********************************************************************
3081 File ..., line 3, in f
3082 Failed example:
3083 print('\n'.join(['a ', 'b']))
3084 Differences (ndiff with -expected +actual):
3085 - a
3086 + a
3087 b
3088 TestResults(failed=1, attempted=1)
3089
3090 *NOTE*: `\x20` is for checking the trailing whitespace on the +a line above.
3091 We cannot use actual spaces there, as a commit hook prevents from committing
3092 patches that contain trailing whitespace. More info on Issue 24746.
3093 """
3094
Tim Peters8485b562004-08-04 18:46:34 +00003095######################################################################
3096## Main
3097######################################################################
3098
3099def test_main():
3100 # Check the doctest cases in doctest itself:
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02003101 ret = support.run_doctest(doctest, verbosity=True)
Victor Stinner931602a2016-03-25 12:48:17 +01003102
Tim Peters8485b562004-08-04 18:46:34 +00003103 # Check the doctest cases defined here:
3104 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003105 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00003106
Jason R. Coombsb9650a02018-03-05 18:29:08 -05003107 # Run unittests
3108 support.run_unittest(__name__)
3109
3110
Tim Peters8485b562004-08-04 18:46:34 +00003111def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00003112 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01003113 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00003114 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00003115 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00003116 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003117 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00003118 r.write_results(show_missing=True, summary=True,
3119 coverdir=coverdir)
3120
3121if __name__ == '__main__':
3122 if '-c' in sys.argv:
3123 test_coverage('/tmp/doctest.cover')
3124 else:
3125 test_main()