blob: 7f8ccd3896ead29357d97a145f8e913f76aadc9d [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Hai Shi46605972020-08-04 00:49:18 +08006from test.support import import_helper
7from test.support import os_helper
Tim Peters8485b562004-08-04 18:46:34 +00008import doctest
Yury Selivanovb532df62014-12-08 15:00:05 -05009import functools
Victor Stinner9d396392010-10-16 21:54:59 +000010import os
Brett Cannon31f59292011-02-21 19:29:56 +000011import sys
Jason R. Coombsb9650a02018-03-05 18:29:08 -050012import importlib
Peter Donise0b81012020-03-26 11:53:16 -040013import importlib.abc
14import importlib.util
Jason R. Coombsb9650a02018-03-05 18:29:08 -050015import unittest
Nick Coghland5d9e022018-03-25 23:03:10 +100016import tempfile
Peter Donise0b81012020-03-26 11:53:16 -040017import shutil
Miss Islington (bot)10d6f6b2021-05-05 11:01:21 -070018import types
Peter Donise0b81012020-03-26 11:53:16 -040019import contextlib
Florent Xiclunadc6f2d02010-04-02 19:25:32 +000020
Nick Coghlanf088e5e2008-12-14 11:50:48 +000021# NOTE: There are some additional tests relating to interaction with
22# zipimport in the test_zipimport_support test module.
23
Tim Peters8485b562004-08-04 18:46:34 +000024######################################################################
25## Sample Objects (used by test cases)
26######################################################################
27
28def sample_func(v):
29 """
Tim Peters19397e52004-08-06 22:02:59 +000030 Blah blah
31
Guido van Rossum7131f842007-02-09 20:13:25 +000032 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000033 44
Tim Peters19397e52004-08-06 22:02:59 +000034
35 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000036 """
37 return v+v
38
39class SampleClass:
40 """
Guido van Rossum7131f842007-02-09 20:13:25 +000041 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000042 1
Edward Loper4ae900f2004-09-21 03:20:34 +000043
44 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
45 >>>
46 ...
47
48 Multiline example:
49 >>> sc = SampleClass(3)
50 >>> for i in range(10):
51 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000052 ... print(' ', sc.get(), sep='', end='')
53 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000054 """
55 def __init__(self, val):
56 """
Guido van Rossum7131f842007-02-09 20:13:25 +000057 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000058 12
59 """
60 self.val = val
61
62 def double(self):
63 """
Guido van Rossum7131f842007-02-09 20:13:25 +000064 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000065 24
66 """
67 return SampleClass(self.val + self.val)
68
69 def get(self):
70 """
Guido van Rossum7131f842007-02-09 20:13:25 +000071 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000072 -5
73 """
74 return self.val
75
76 def a_staticmethod(v):
77 """
Guido van Rossum7131f842007-02-09 20:13:25 +000078 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000079 11
80 """
81 return v+1
82 a_staticmethod = staticmethod(a_staticmethod)
83
84 def a_classmethod(cls, v):
85 """
Guido van Rossum7131f842007-02-09 20:13:25 +000086 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000087 12
Guido van Rossum7131f842007-02-09 20:13:25 +000088 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000089 12
90 """
91 return v+2
92 a_classmethod = classmethod(a_classmethod)
93
94 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000095 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000096 22
97 """)
98
99 class NestedClass:
100 """
101 >>> x = SampleClass.NestedClass(5)
102 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +0000103 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +0000104 25
105 """
106 def __init__(self, val=0):
107 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000108 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +0000109 0
110 """
111 self.val = val
112 def square(self):
113 return SampleClass.NestedClass(self.val*self.val)
114 def get(self):
115 return self.val
116
117class SampleNewStyleClass(object):
118 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000119 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000120 1
121 2
122 3
123 """
124 def __init__(self, val):
125 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000126 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000127 12
128 """
129 self.val = val
130
131 def double(self):
132 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000133 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000134 24
135 """
136 return SampleNewStyleClass(self.val + self.val)
137
138 def get(self):
139 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000140 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000141 -5
142 """
143 return self.val
144
145######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000146## Fake stdin (for testing interactive debugging)
147######################################################################
148
149class _FakeInput:
150 """
151 A fake input stream for pdb's interactive debugger. Whenever a
152 line is read, print it (to simulate the user typing it), and then
153 return it. The set of lines to return is specified in the
154 constructor; they should not have trailing newlines.
155 """
156 def __init__(self, lines):
157 self.lines = lines
158
159 def readline(self):
160 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000161 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000162 return line+'\n'
163
164######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000165## Test Cases
166######################################################################
167
168def test_Example(): r"""
169Unit tests for the `Example` class.
170
Edward Lopera6b68322004-08-26 00:05:43 +0000171Example is a simple container class that holds:
172 - `source`: A source string.
173 - `want`: An expected output string.
174 - `exc_msg`: An expected exception message string (or None if no
175 exception is expected).
176 - `lineno`: A line number (within the docstring).
177 - `indent`: The example's indentation in the input string.
178 - `options`: An option dictionary, mapping option flags to True or
179 False.
Tim Peters8485b562004-08-04 18:46:34 +0000180
Edward Lopera6b68322004-08-26 00:05:43 +0000181These attributes are set by the constructor. `source` and `want` are
182required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000183
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000184 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000185 >>> (example.source, example.want, example.exc_msg,
186 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000187 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000188
189The first three attributes (`source`, `want`, and `exc_msg`) may be
190specified positionally; the remaining arguments should be specified as
191keyword arguments:
192
193 >>> exc_msg = 'IndexError: pop from an empty list'
194 >>> example = doctest.Example('[].pop()', '', exc_msg,
195 ... lineno=5, indent=4,
196 ... options={doctest.ELLIPSIS: True})
197 >>> (example.source, example.want, example.exc_msg,
198 ... example.lineno, example.indent, example.options)
199 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
200
201The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000202
Tim Petersbb431472004-08-09 03:51:46 +0000203 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000204 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000205 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000206 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000207
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000208 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000209 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000210 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000211
Tim Petersbb431472004-08-09 03:51:46 +0000212 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000213 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000214 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000215 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000216
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000217 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000218 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000219 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000220
Edward Lopera6b68322004-08-26 00:05:43 +0000221 Empty source string (which should never appear in real examples)
222 >>> e = doctest.Example('', '')
223 >>> e.source, e.want
224 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000225
Edward Lopera6b68322004-08-26 00:05:43 +0000226The constructor normalizes the `want` string to end in a newline,
227unless it's the empty string:
228
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000229 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000230 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000231 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000232
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000233 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000234 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000235 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000236
Edward Lopera6b68322004-08-26 00:05:43 +0000237 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000238 >>> e.source, e.want
239 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000240
241The constructor normalizes the `exc_msg` string to end in a newline,
242unless it's `None`:
243
244 Message spans one line
245 >>> exc_msg = 'IndexError: pop from an empty list'
246 >>> e = doctest.Example('[].pop()', '', exc_msg)
247 >>> e.exc_msg
248 'IndexError: pop from an empty list\n'
249
250 >>> exc_msg = 'IndexError: pop from an empty list\n'
251 >>> e = doctest.Example('[].pop()', '', exc_msg)
252 >>> e.exc_msg
253 'IndexError: pop from an empty list\n'
254
255 Message spans multiple lines
256 >>> exc_msg = 'ValueError: 1\n 2'
257 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
258 >>> e.exc_msg
259 'ValueError: 1\n 2\n'
260
261 >>> exc_msg = 'ValueError: 1\n 2\n'
262 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
263 >>> e.exc_msg
264 'ValueError: 1\n 2\n'
265
266 Empty (but non-None) exception message (which should never appear
267 in real examples)
268 >>> exc_msg = ''
269 >>> e = doctest.Example('raise X()', '', exc_msg)
270 >>> e.exc_msg
271 '\n'
Antoine Pitrou165b1282011-12-18 20:20:17 +0100272
273Compare `Example`:
274 >>> example = doctest.Example('print 1', '1\n')
275 >>> same_example = doctest.Example('print 1', '1\n')
276 >>> other_example = doctest.Example('print 42', '42\n')
277 >>> example == same_example
278 True
279 >>> example != same_example
280 False
281 >>> hash(example) == hash(same_example)
282 True
283 >>> example == other_example
284 False
285 >>> example != other_example
286 True
Tim Peters8485b562004-08-04 18:46:34 +0000287"""
288
289def test_DocTest(): r"""
290Unit tests for the `DocTest` class.
291
292DocTest is a collection of examples, extracted from a docstring, along
293with information about where the docstring comes from (a name,
294filename, and line number). The docstring is parsed by the `DocTest`
295constructor:
296
297 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000298 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000299 ... 12
300 ...
301 ... Non-example text.
302 ...
R David Murray44b548d2016-09-08 13:59:53 -0400303 ... >>> print('another\\example')
Tim Peters8485b562004-08-04 18:46:34 +0000304 ... another
305 ... example
306 ... '''
307 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000308 >>> parser = doctest.DocTestParser()
309 >>> test = parser.get_doctest(docstring, globs, 'some_test',
310 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000311 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000312 <DocTest some_test from some_file:20 (2 examples)>
313 >>> len(test.examples)
314 2
315 >>> e1, e2 = test.examples
316 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000317 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000318 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000319 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000320
321Source information (name, filename, and line number) is available as
322attributes on the doctest object:
323
324 >>> (test.name, test.filename, test.lineno)
325 ('some_test', 'some_file', 20)
326
327The line number of an example within its containing file is found by
328adding the line number of the example and the line number of its
329containing test:
330
331 >>> test.lineno + e1.lineno
332 21
333 >>> test.lineno + e2.lineno
334 26
335
Martin Panter46f50722016-05-26 05:35:26 +0000336If the docstring contains inconsistent leading whitespace in the
Tim Peters8485b562004-08-04 18:46:34 +0000337expected output of an example, then `DocTest` will raise a ValueError:
338
339 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000340 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000341 ... bad
342 ... indentation
343 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000344 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000345 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000346 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000347
348If the docstring contains inconsistent leading whitespace on
349continuation lines, then `DocTest` will raise a ValueError:
350
351 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000352 ... >>> print(('bad indentation',
353 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000354 ... ('bad', 'indentation')
355 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000356 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000357 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000358 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000359
360If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
361will raise a ValueError:
362
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000363 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000364 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000365 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000366 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000367
368If there's no blank space after a PS2 prompt ('...'), then `DocTest`
369will raise a ValueError:
370
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000371 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000372 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000373 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000374 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000375
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100376Compare `DocTest`:
377
378 >>> docstring = '''
379 ... >>> print 12
380 ... 12
381 ... '''
382 >>> test = parser.get_doctest(docstring, globs, 'some_test',
383 ... 'some_test', 20)
384 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
385 ... 'some_test', 20)
386 >>> test == same_test
387 True
388 >>> test != same_test
389 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100390 >>> hash(test) == hash(same_test)
391 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100392 >>> docstring = '''
393 ... >>> print 42
394 ... 42
395 ... '''
396 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
397 ... 'other_file', 10)
398 >>> test == other_test
399 False
400 >>> test != other_test
401 True
402
403Compare `DocTestCase`:
404
405 >>> DocTestCase = doctest.DocTestCase
406 >>> test_case = DocTestCase(test)
407 >>> same_test_case = DocTestCase(same_test)
408 >>> other_test_case = DocTestCase(other_test)
409 >>> test_case == same_test_case
410 True
411 >>> test_case != same_test_case
412 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100413 >>> hash(test_case) == hash(same_test_case)
414 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100415 >>> test == other_test_case
416 False
417 >>> test != other_test_case
418 True
419
Tim Peters8485b562004-08-04 18:46:34 +0000420"""
421
Zachary Ware7119b452013-11-24 02:21:57 -0600422class test_DocTestFinder:
423 def basics(): r"""
Tim Peters8485b562004-08-04 18:46:34 +0000424Unit tests for the `DocTestFinder` class.
425
426DocTestFinder is used to extract DocTests from an object's docstring
427and the docstrings of its contained objects. It can be used with
428modules, functions, classes, methods, staticmethods, classmethods, and
429properties.
430
431Finding Tests in Functions
432~~~~~~~~~~~~~~~~~~~~~~~~~~
433For a function whose docstring contains examples, DocTestFinder.find()
434will return a single test (for that function's docstring):
435
Tim Peters8485b562004-08-04 18:46:34 +0000436 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000437
438We'll simulate a __file__ attr that ends in pyc:
439
440 >>> import test.test_doctest
441 >>> old = test.test_doctest.__file__
442 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
443
Tim Peters8485b562004-08-04 18:46:34 +0000444 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000445
Guido van Rossum7131f842007-02-09 20:13:25 +0000446 >>> print(tests) # doctest: +ELLIPSIS
Miss Islington (bot)10d6f6b2021-05-05 11:01:21 -0700447 [<DocTest sample_func from test_doctest.py:28 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000448
Tim Peters4de7c5c2004-08-23 22:38:05 +0000449The exact name depends on how test_doctest was invoked, so allow for
450leading path components.
451
452 >>> tests[0].filename # doctest: +ELLIPSIS
453 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000454
455 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000456
Jim Fulton07a349c2004-08-22 14:10:00 +0000457
Tim Peters8485b562004-08-04 18:46:34 +0000458 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000459 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000460 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000461
Edward Loper32ddbf72004-09-13 05:47:24 +0000462By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000463
464 >>> def no_docstring(v):
465 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000466 >>> finder.find(no_docstring)
467 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000468
469However, the optional argument `exclude_empty` to the DocTestFinder
470constructor can be used to exclude tests for objects with empty
471docstrings:
472
473 >>> def no_docstring(v):
474 ... pass
475 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
476 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000477 []
478
479If the function has a docstring with no examples, then a test with no
480examples is returned. (This lets `DocTestRunner` collect statistics
481about which functions have no tests -- but is that useful? And should
482an empty test also be created when there's no docstring?)
483
484 >>> def no_examples(v):
485 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000486 >>> finder.find(no_examples) # doctest: +ELLIPSIS
487 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000488
489Finding Tests in Classes
490~~~~~~~~~~~~~~~~~~~~~~~~
491For a class, DocTestFinder will create a test for the class's
492docstring, and will recursively explore its contents, including
493methods, classmethods, staticmethods, properties, and nested classes.
494
495 >>> finder = doctest.DocTestFinder()
496 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000497 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000498 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000499 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000500 3 SampleClass.NestedClass
501 1 SampleClass.NestedClass.__init__
502 1 SampleClass.__init__
503 2 SampleClass.a_classmethod
504 1 SampleClass.a_property
505 1 SampleClass.a_staticmethod
506 1 SampleClass.double
507 1 SampleClass.get
508
509New-style classes are also supported:
510
511 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000512 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000513 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000514 1 SampleNewStyleClass
515 1 SampleNewStyleClass.__init__
516 1 SampleNewStyleClass.double
517 1 SampleNewStyleClass.get
518
519Finding Tests in Modules
520~~~~~~~~~~~~~~~~~~~~~~~~
521For a module, DocTestFinder will create a test for the class's
522docstring, and will recursively explore its contents, including
523functions, classes, and the `__test__` dictionary, if it exists:
524
525 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000526 >>> import types
527 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000528 >>> def triple(val):
529 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000530 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000531 ... 33
532 ... '''
533 ... return val*3
534 >>> m.__dict__.update({
535 ... 'sample_func': sample_func,
536 ... 'SampleClass': SampleClass,
537 ... '__doc__': '''
538 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000539 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000540 ... module
541 ... ''',
542 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000543 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000544 ... 'c': triple}})
545
546 >>> finder = doctest.DocTestFinder()
547 >>> # Use module=test.test_doctest, to prevent doctest from
548 >>> # ignoring the objects since they weren't defined in m.
549 >>> import test.test_doctest
550 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000551 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000552 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000553 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000554 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000555 3 some_module.SampleClass.NestedClass
556 1 some_module.SampleClass.NestedClass.__init__
557 1 some_module.SampleClass.__init__
558 2 some_module.SampleClass.a_classmethod
559 1 some_module.SampleClass.a_property
560 1 some_module.SampleClass.a_staticmethod
561 1 some_module.SampleClass.double
562 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000563 1 some_module.__test__.c
564 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000565 1 some_module.sample_func
566
567Duplicate Removal
568~~~~~~~~~~~~~~~~~
569If a single object is listed twice (under different names), then tests
570will only be generated for it once:
571
Tim Petersf3f57472004-08-08 06:11:48 +0000572 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000573 >>> assert doctest_aliases.TwoNames.f
574 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000575 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000576 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000577 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000578 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000579 test.doctest_aliases.TwoNames
580
581 TwoNames.f and TwoNames.g are bound to the same object.
582 We can't guess which will be found in doctest's traversal of
583 TwoNames.__dict__ first, so we have to allow for either.
584
585 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000586 True
587
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000588Empty Tests
589~~~~~~~~~~~
590By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000591
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000592 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000593 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000594 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000595 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000596 3 SampleClass.NestedClass
597 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000598 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000599 2 SampleClass.a_classmethod
600 1 SampleClass.a_property
601 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000602 1 SampleClass.double
603 1 SampleClass.get
604
605By default, that excluded objects with no doctests. exclude_empty=False
606tells it to include (empty) tests for objects with no doctests. This feature
607is really to support backward compatibility in what doctest.master.summarize()
608displays.
609
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000610 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000611 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000612 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000613 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000614 3 SampleClass.NestedClass
615 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000616 0 SampleClass.NestedClass.get
617 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000618 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000619 2 SampleClass.a_classmethod
620 1 SampleClass.a_property
621 1 SampleClass.a_staticmethod
622 1 SampleClass.double
623 1 SampleClass.get
624
Tim Peters8485b562004-08-04 18:46:34 +0000625Turning off Recursion
626~~~~~~~~~~~~~~~~~~~~~
627DocTestFinder can be told not to look for tests in contained objects
628using the `recurse` flag:
629
630 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000631 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000632 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000633 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000634
635Line numbers
636~~~~~~~~~~~~
637DocTestFinder finds the line number of each example:
638
639 >>> def f(x):
640 ... '''
641 ... >>> x = 12
642 ...
643 ... some text
644 ...
645 ... >>> # examples are not created for comments & bare prompts.
646 ... >>>
647 ... ...
648 ...
649 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000650 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000651 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000652 ... >>> x//2
653 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000654 ... '''
655 >>> test = doctest.DocTestFinder().find(f)[0]
656 >>> [e.lineno for e in test.examples]
657 [1, 9, 12]
Zachary Ware7119b452013-11-24 02:21:57 -0600658"""
659
660 if int.__doc__: # simple check for --without-doc-strings, skip if lacking
661 def non_Python_modules(): r"""
Zachary Warea4b7a752013-11-24 01:19:09 -0600662
663Finding Doctests in Modules Not Written in Python
664~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
665DocTestFinder can also find doctests in most modules not written in Python.
666We'll use builtins as an example, since it almost certainly isn't written in
667plain ol' Python and is guaranteed to be available.
668
669 >>> import builtins
670 >>> tests = doctest.DocTestFinder().find(builtins)
sweeneydea81849b2020-04-22 17:05:48 -0400671 >>> 816 < len(tests) < 836 # approximate number of objects with docstrings
Zachary Ware7119b452013-11-24 02:21:57 -0600672 True
Zachary Warea4b7a752013-11-24 01:19:09 -0600673 >>> real_tests = [t for t in tests if len(t.examples) > 0]
Zachary Ware7119b452013-11-24 02:21:57 -0600674 >>> len(real_tests) # objects that actually have doctests
Niklas Fiekas8bd216d2020-05-29 18:28:02 +0200675 14
Zachary Warea4b7a752013-11-24 01:19:09 -0600676 >>> for t in real_tests:
677 ... print('{} {}'.format(len(t.examples), t.name))
678 ...
679 1 builtins.bin
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700680 5 builtins.bytearray.hex
681 5 builtins.bytes.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600682 3 builtins.float.as_integer_ratio
683 2 builtins.float.fromhex
684 2 builtins.float.hex
685 1 builtins.hex
686 1 builtins.int
Lisa Roach5ac70432018-09-13 23:56:23 -0700687 3 builtins.int.as_integer_ratio
Niklas Fiekas8bd216d2020-05-29 18:28:02 +0200688 2 builtins.int.bit_count
Zachary Warea4b7a752013-11-24 01:19:09 -0600689 2 builtins.int.bit_length
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700690 5 builtins.memoryview.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600691 1 builtins.oct
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -0700692 1 builtins.zip
Zachary Warea4b7a752013-11-24 01:19:09 -0600693
694Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
695'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
696and 'int' is a type.
Tim Peters8485b562004-08-04 18:46:34 +0000697"""
698
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500699
700class TestDocTestFinder(unittest.TestCase):
701
Miss Islington (bot)10d6f6b2021-05-05 11:01:21 -0700702 def test_issue35753(self):
703 # This import of `call` should trigger issue35753 when
704 # `support.run_doctest` is called due to unwrap failing,
705 # however with a patched doctest this should succeed.
706 from unittest.mock import call
707 dummy_module = types.ModuleType("dummy")
708 dummy_module.__dict__['inject_call'] = call
709 try:
710 support.run_doctest(dummy_module, verbosity=True)
711 except ValueError as e:
712 raise support.TestFailed("Doctest unwrap failed") from e
713
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500714 def test_empty_namespace_package(self):
715 pkg_name = 'doctest_empty_pkg'
Nick Coghland5d9e022018-03-25 23:03:10 +1000716 with tempfile.TemporaryDirectory() as parent_dir:
717 pkg_dir = os.path.join(parent_dir, pkg_name)
718 os.mkdir(pkg_dir)
719 sys.path.append(parent_dir)
720 try:
721 mod = importlib.import_module(pkg_name)
722 finally:
Hai Shi46605972020-08-04 00:49:18 +0800723 import_helper.forget(pkg_name)
Nick Coghland5d9e022018-03-25 23:03:10 +1000724 sys.path.pop()
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500725
Xtreak8289e272019-12-13 23:36:53 +0530726 include_empty_finder = doctest.DocTestFinder(exclude_empty=False)
727 exclude_empty_finder = doctest.DocTestFinder(exclude_empty=True)
728
729 self.assertEqual(len(include_empty_finder.find(mod)), 1)
730 self.assertEqual(len(exclude_empty_finder.find(mod)), 0)
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500731
Edward Loper00f8da72004-08-26 18:05:07 +0000732def test_DocTestParser(): r"""
733Unit tests for the `DocTestParser` class.
734
735DocTestParser is used to parse docstrings containing doctest examples.
736
737The `parse` method divides a docstring into examples and intervening
738text:
739
740 >>> s = '''
741 ... >>> x, y = 2, 3 # no output expected
742 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000743 ... ... print(x)
744 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000745 ... 2
746 ... 3
747 ...
748 ... Some text.
749 ... >>> x+y
750 ... 5
751 ... '''
752 >>> parser = doctest.DocTestParser()
753 >>> for piece in parser.parse(s):
754 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000755 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000756 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000757 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000758 Text: '\n'
759 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
760 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000761 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000762 Text: '\nSome text.\n'
763 Example: ('x+y\n', '5\n', 9)
764 Text: ''
765
766The `get_examples` method returns just the examples:
767
768 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000769 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000770 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000771 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000772 ('x+y\n', '5\n', 9)
773
774The `get_doctest` method creates a Test from the examples, along with the
775given arguments:
776
777 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
778 >>> (test.name, test.filename, test.lineno)
779 ('name', 'filename', 5)
780 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000781 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000782 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000783 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000784 ('x+y\n', '5\n', 9)
785"""
786
Tim Peters8485b562004-08-04 18:46:34 +0000787class test_DocTestRunner:
788 def basics(): r"""
789Unit tests for the `DocTestRunner` class.
790
791DocTestRunner is used to run DocTest test cases, and to accumulate
792statistics. Here's a simple DocTest case we can use:
793
794 >>> def f(x):
795 ... '''
796 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000797 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000798 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000799 ... >>> x//2
800 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000801 ... '''
802 >>> test = doctest.DocTestFinder().find(f)[0]
803
804The main DocTestRunner interface is the `run` method, which runs a
805given DocTest case in a given namespace (globs). It returns a tuple
806`(f,t)`, where `f` is the number of failed tests and `t` is the number
807of tried tests.
808
809 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000810 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000811
812If any example produces incorrect output, then the test runner reports
813the failure and proceeds to the next example:
814
815 >>> def f(x):
816 ... '''
817 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000818 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000819 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000820 ... >>> x//2
821 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000822 ... '''
823 >>> test = doctest.DocTestFinder().find(f)[0]
824 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000825 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000826 Trying:
827 x = 12
828 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000829 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000830 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000831 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000832 Expecting:
833 14
Tim Peters8485b562004-08-04 18:46:34 +0000834 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000835 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000836 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000837 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000838 Expected:
839 14
840 Got:
841 12
Edward Loperaacf0832004-08-26 01:19:50 +0000842 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000843 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000844 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845 6
Tim Peters8485b562004-08-04 18:46:34 +0000846 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000847 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000848"""
849 def verbose_flag(): r"""
850The `verbose` flag makes the test runner generate more detailed
851output:
852
853 >>> def f(x):
854 ... '''
855 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000856 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000857 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000858 ... >>> x//2
859 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000860 ... '''
861 >>> test = doctest.DocTestFinder().find(f)[0]
862
863 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000864 Trying:
865 x = 12
866 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000867 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000868 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000869 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000870 Expecting:
871 12
Tim Peters8485b562004-08-04 18:46:34 +0000872 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000873 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000874 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000875 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000876 6
Tim Peters8485b562004-08-04 18:46:34 +0000877 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000878 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000879
880If the `verbose` flag is unspecified, then the output will be verbose
881iff `-v` appears in sys.argv:
882
883 >>> # Save the real sys.argv list.
884 >>> old_argv = sys.argv
885
886 >>> # If -v does not appear in sys.argv, then output isn't verbose.
887 >>> sys.argv = ['test']
888 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000889 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000890
891 >>> # If -v does appear in sys.argv, then output is verbose.
892 >>> sys.argv = ['test', '-v']
893 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000894 Trying:
895 x = 12
896 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000897 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000898 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000899 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000900 Expecting:
901 12
Tim Peters8485b562004-08-04 18:46:34 +0000902 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000903 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000904 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000905 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000906 6
Tim Peters8485b562004-08-04 18:46:34 +0000907 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000908 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000909
910 >>> # Restore sys.argv
911 >>> sys.argv = old_argv
912
913In the remaining examples, the test runner's verbosity will be
914explicitly set, to ensure that the test behavior is consistent.
915 """
916 def exceptions(): r"""
917Tests of `DocTestRunner`'s exception handling.
918
919An expected exception is specified with a traceback message. The
920lines between the first line and the type/value may be omitted or
921replaced with any other string:
922
923 >>> def f(x):
924 ... '''
925 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000926 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000927 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000928 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000929 ... '''
930 >>> test = doctest.DocTestFinder().find(f)[0]
931 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000932 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000933
Edward Loper19b19582004-08-25 23:07:03 +0000934An example may not generate output before it raises an exception; if
935it does, then the traceback message will not be recognized as
936signaling an expected exception, so the example will be reported as an
937unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000938
939 >>> def f(x):
940 ... '''
941 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000942 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000943 ... pre-exception output
944 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000945 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000946 ... '''
947 >>> test = doctest.DocTestFinder().find(f)[0]
948 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000949 ... # doctest: +ELLIPSIS
950 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000951 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000952 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000953 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000954 Exception raised:
955 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000956 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000957 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000958
959Exception messages may contain newlines:
960
961 >>> def f(x):
962 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000963 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000964 ... Traceback (most recent call last):
965 ... ValueError: multi
966 ... line
967 ... message
968 ... '''
969 >>> test = doctest.DocTestFinder().find(f)[0]
970 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000971 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000972
973If an exception is expected, but an exception with the wrong type or
974message is raised, then it is reported as a failure:
975
976 >>> def f(x):
977 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000978 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000979 ... Traceback (most recent call last):
980 ... ValueError: wrong message
981 ... '''
982 >>> test = doctest.DocTestFinder().find(f)[0]
983 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000984 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000985 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000986 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000987 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000988 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000989 Expected:
990 Traceback (most recent call last):
991 ValueError: wrong message
992 Got:
993 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000994 ...
Tim Peters8485b562004-08-04 18:46:34 +0000995 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000996 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000997
Tim Peters1fbf9c52004-09-04 17:21:02 +0000998However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
999detail:
1000
1001 >>> def f(x):
1002 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001003 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001004 ... Traceback (most recent call last):
1005 ... ValueError: wrong message
1006 ... '''
1007 >>> test = doctest.DocTestFinder().find(f)[0]
1008 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001009 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001010
Nick Coghlan5e76e942010-06-12 13:42:46 +00001011IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
1012between Python versions. For example, in Python 2.x, the module path of
1013the exception is not in the output, but this will fail under Python 3:
1014
1015 >>> def f(x):
1016 ... r'''
1017 ... >>> from http.client import HTTPException
1018 ... >>> raise HTTPException('message')
1019 ... Traceback (most recent call last):
1020 ... HTTPException: message
1021 ... '''
1022 >>> test = doctest.DocTestFinder().find(f)[0]
1023 >>> doctest.DocTestRunner(verbose=False).run(test)
1024 ... # doctest: +ELLIPSIS
1025 **********************************************************************
1026 File ..., line 4, in f
1027 Failed example:
1028 raise HTTPException('message')
1029 Expected:
1030 Traceback (most recent call last):
1031 HTTPException: message
1032 Got:
1033 Traceback (most recent call last):
1034 ...
1035 http.client.HTTPException: message
1036 TestResults(failed=1, attempted=2)
1037
1038But in Python 3 the module path is included, and therefore a test must look
1039like the following test to succeed in Python 3. But that test will fail under
1040Python 2.
1041
1042 >>> def f(x):
1043 ... r'''
1044 ... >>> from http.client import HTTPException
1045 ... >>> raise HTTPException('message')
1046 ... Traceback (most recent call last):
1047 ... http.client.HTTPException: message
1048 ... '''
1049 >>> test = doctest.DocTestFinder().find(f)[0]
1050 >>> doctest.DocTestRunner(verbose=False).run(test)
1051 TestResults(failed=0, attempted=2)
1052
1053However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1054(or its unexpected absence) will be ignored:
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 ... HTTPException: message
1062 ... '''
1063 >>> test = doctest.DocTestFinder().find(f)[0]
1064 >>> doctest.DocTestRunner(verbose=False).run(test)
1065 TestResults(failed=0, attempted=2)
1066
1067The module path will be completely ignored, so two different module paths will
1068still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1069be used when exceptions have changed module.
1070
1071 >>> def f(x):
1072 ... r'''
1073 ... >>> from http.client import HTTPException
1074 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1075 ... Traceback (most recent call last):
1076 ... foo.bar.HTTPException: message
1077 ... '''
1078 >>> test = doctest.DocTestFinder().find(f)[0]
1079 >>> doctest.DocTestRunner(verbose=False).run(test)
1080 TestResults(failed=0, attempted=2)
1081
Tim Peters1fbf9c52004-09-04 17:21:02 +00001082But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1083
1084 >>> def f(x):
1085 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001086 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001087 ... Traceback (most recent call last):
1088 ... TypeError: wrong type
1089 ... '''
1090 >>> test = doctest.DocTestFinder().find(f)[0]
1091 >>> doctest.DocTestRunner(verbose=False).run(test)
1092 ... # doctest: +ELLIPSIS
1093 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001094 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001095 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001096 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001097 Expected:
1098 Traceback (most recent call last):
1099 TypeError: wrong type
1100 Got:
1101 Traceback (most recent call last):
1102 ...
1103 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001104 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001105
Tim Petersf9a07f22013-12-03 21:02:05 -06001106If the exception does not have a message, you can still use
1107IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1108
1109 >>> def f(x):
1110 ... r'''
1111 ... >>> from http.client import HTTPException
1112 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1113 ... Traceback (most recent call last):
1114 ... foo.bar.HTTPException
1115 ... '''
1116 >>> test = doctest.DocTestFinder().find(f)[0]
1117 >>> doctest.DocTestRunner(verbose=False).run(test)
1118 TestResults(failed=0, attempted=2)
1119
1120Note that a trailing colon doesn't matter either:
1121
1122 >>> def f(x):
1123 ... r'''
1124 ... >>> from http.client import HTTPException
1125 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1126 ... Traceback (most recent call last):
1127 ... foo.bar.HTTPException:
1128 ... '''
1129 >>> test = doctest.DocTestFinder().find(f)[0]
1130 >>> doctest.DocTestRunner(verbose=False).run(test)
1131 TestResults(failed=0, attempted=2)
1132
Tim Peters8485b562004-08-04 18:46:34 +00001133If an exception is raised but not expected, then it is reported as an
1134unexpected exception:
1135
Tim Peters8485b562004-08-04 18:46:34 +00001136 >>> def f(x):
1137 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001138 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001139 ... 0
1140 ... '''
1141 >>> test = doctest.DocTestFinder().find(f)[0]
1142 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001143 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001144 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001145 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001146 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001147 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001148 Exception raised:
1149 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001150 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001151 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001152 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001153"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001154 def displayhook(): r"""
1155Test that changing sys.displayhook doesn't matter for doctest.
1156
1157 >>> import sys
1158 >>> orig_displayhook = sys.displayhook
1159 >>> def my_displayhook(x):
1160 ... print('hi!')
1161 >>> sys.displayhook = my_displayhook
1162 >>> def f():
1163 ... '''
1164 ... >>> 3
1165 ... 3
1166 ... '''
1167 >>> test = doctest.DocTestFinder().find(f)[0]
1168 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1169 >>> post_displayhook = sys.displayhook
1170
1171 We need to restore sys.displayhook now, so that we'll be able to test
1172 results.
1173
1174 >>> sys.displayhook = orig_displayhook
1175
1176 Ok, now we can check that everything is ok.
1177
1178 >>> r
1179 TestResults(failed=0, attempted=1)
1180 >>> post_displayhook is my_displayhook
1181 True
1182"""
Tim Peters8485b562004-08-04 18:46:34 +00001183 def optionflags(): r"""
1184Tests of `DocTestRunner`'s option flag handling.
1185
1186Several option flags can be used to customize the behavior of the test
1187runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001188to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001189together).
1190
1191The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1192and 1/0:
1193
1194 >>> def f(x):
1195 ... '>>> True\n1\n'
1196
1197 >>> # Without the flag:
1198 >>> test = doctest.DocTestFinder().find(f)[0]
1199 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001200 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001201
1202 >>> # With the flag:
1203 >>> test = doctest.DocTestFinder().find(f)[0]
1204 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1205 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001206 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001207 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001208 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001209 Failed example:
1210 True
1211 Expected:
1212 1
1213 Got:
1214 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001215 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001216
1217The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1218and the '<BLANKLINE>' marker:
1219
1220 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001221 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001222
1223 >>> # Without the flag:
1224 >>> test = doctest.DocTestFinder().find(f)[0]
1225 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001226 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001227
1228 >>> # With the flag:
1229 >>> test = doctest.DocTestFinder().find(f)[0]
1230 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1231 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001232 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001233 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001234 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001235 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001236 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001237 Expected:
1238 a
1239 <BLANKLINE>
1240 b
1241 Got:
1242 a
1243 <BLANKLINE>
1244 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001245 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001246
1247The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1248treated as equal:
1249
1250 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001251 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001252
1253 >>> # Without the flag:
1254 >>> test = doctest.DocTestFinder().find(f)[0]
1255 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001256 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001257 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001258 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001259 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001260 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001261 Expected:
1262 1 2
1263 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001264 Got:
1265 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001266 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001267
1268 >>> # With the flag:
1269 >>> test = doctest.DocTestFinder().find(f)[0]
1270 >>> flags = doctest.NORMALIZE_WHITESPACE
1271 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001272 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001273
Tim Peters026f8dc2004-08-19 16:38:58 +00001274 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001275 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001276 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1277 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1278
Tim Peters8485b562004-08-04 18:46:34 +00001279The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1280output to match any substring in the actual output:
1281
1282 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001283 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001284
1285 >>> # Without the flag:
1286 >>> test = doctest.DocTestFinder().find(f)[0]
1287 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001288 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001289 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001290 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001291 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001292 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001293 Expected:
1294 [0, 1, 2, ..., 14]
1295 Got:
1296 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001297 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001298
1299 >>> # With the flag:
1300 >>> test = doctest.DocTestFinder().find(f)[0]
1301 >>> flags = doctest.ELLIPSIS
1302 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001303 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001304
Tim Peterse594bee2004-08-22 01:47:51 +00001305 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001306
Guido van Rossume0192e52007-02-09 23:39:59 +00001307 >>> if 1:
1308 ... for i in range(100):
1309 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1310 ... print('!')
1311 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001312
Tim Peters026f8dc2004-08-19 16:38:58 +00001313 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001314
Guido van Rossume0192e52007-02-09 23:39:59 +00001315 >>> if 1: #doctest: +ELLIPSIS
1316 ... for i in range(20):
1317 ... print(i, end=' ')
1318 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001319 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001320
Tim Peters026f8dc2004-08-19 16:38:58 +00001321 Examples from the docs:
1322
Guido van Rossum805365e2007-05-07 22:24:25 +00001323 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001324 [0, 1, ..., 18, 19]
1325
Guido van Rossum805365e2007-05-07 22:24:25 +00001326 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001327 ... # doctest: +NORMALIZE_WHITESPACE
1328 [0, 1, ..., 18, 19]
1329
Thomas Wouters477c8d52006-05-27 19:21:47 +00001330The SKIP flag causes an example to be skipped entirely. I.e., the
1331example is not run. It can be useful in contexts where doctest
1332examples serve as both documentation and test cases, and an example
1333should be included for documentation purposes, but should not be
1334checked (e.g., because its output is random, or depends on resources
1335which would be unavailable.) The SKIP flag can also be used for
1336'commenting out' broken examples.
1337
1338 >>> import unavailable_resource # doctest: +SKIP
1339 >>> unavailable_resource.do_something() # doctest: +SKIP
1340 >>> unavailable_resource.blow_up() # doctest: +SKIP
1341 Traceback (most recent call last):
1342 ...
1343 UncheckedBlowUpError: Nobody checks me.
1344
1345 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001346 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001347 0.721216923889
1348
Edward Loper71f55af2004-08-26 01:41:51 +00001349The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001350and actual outputs to be displayed using a unified diff:
1351
1352 >>> def f(x):
1353 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001354 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001355 ... a
1356 ... B
1357 ... c
1358 ... d
1359 ... f
1360 ... g
1361 ... h
1362 ... '''
1363
1364 >>> # Without the flag:
1365 >>> test = doctest.DocTestFinder().find(f)[0]
1366 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001367 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001368 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001369 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001370 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001371 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001372 Expected:
1373 a
1374 B
1375 c
1376 d
1377 f
1378 g
1379 h
1380 Got:
1381 a
1382 b
1383 c
1384 d
1385 e
1386 f
1387 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001388 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001389
1390 >>> # With the flag:
1391 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001392 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001393 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001394 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001395 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001396 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001397 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001398 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001399 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001400 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001401 a
1402 -B
1403 +b
1404 c
1405 d
1406 +e
1407 f
1408 g
1409 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001410 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001411
Edward Loper71f55af2004-08-26 01:41:51 +00001412The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001413and actual outputs to be displayed using a context diff:
1414
Edward Loper71f55af2004-08-26 01:41:51 +00001415 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001416 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001417 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001418 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001419 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001420 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001421 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001422 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001423 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001424 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001425 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001426 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001427 a
1428 ! B
1429 c
1430 d
1431 f
1432 g
1433 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001434 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001435 a
1436 ! b
1437 c
1438 d
1439 + e
1440 f
1441 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001442 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001443
1444
Edward Loper71f55af2004-08-26 01:41:51 +00001445The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001446used by the popular ndiff.py utility. This does intraline difference
1447marking, as well as interline differences.
1448
1449 >>> def f(x):
1450 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001451 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001452 ... a b c d e f g h i j k 1 m
1453 ... '''
1454 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001455 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001456 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001457 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001458 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001459 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001460 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001461 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001462 Differences (ndiff with -expected +actual):
1463 - a b c d e f g h i j k 1 m
1464 ? ^
1465 + a b c d e f g h i j k l m
1466 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001467 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001468
Ezio Melotti13925002011-03-16 11:05:33 +02001469The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001470failing example:
1471
1472 >>> def f(x):
1473 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001474 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001475 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001476 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001477 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001478 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001479 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001480 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001481 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001482 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001483 ... 500
1484 ... '''
1485 >>> test = doctest.DocTestFinder().find(f)[0]
1486 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1487 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001488 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001489 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001490 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001491 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001492 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001493 Expected:
1494 200
1495 Got:
1496 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001497 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001498
Ezio Melotti13925002011-03-16 11:05:33 +02001499However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001500
1501 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001502 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001503 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001504 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001505 Expecting:
1506 1
1507 ok
1508 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001509 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001510 Expecting:
1511 200
1512 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001513 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001514 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001515 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001516 Expected:
1517 200
1518 Got:
1519 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001520 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001521
R David Murray5a9d7062012-11-21 15:09:21 -05001522The FAIL_FAST flag causes the runner to exit after the first failing example,
1523so subsequent examples are not even attempted:
1524
1525 >>> flags = doctest.FAIL_FAST
1526 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1527 ... # doctest: +ELLIPSIS
1528 **********************************************************************
1529 File ..., line 5, in f
1530 Failed example:
1531 print(2) # first failure
1532 Expected:
1533 200
1534 Got:
1535 2
1536 TestResults(failed=1, attempted=2)
1537
1538Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1539FAIL_FAST only:
1540
1541 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1542 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1543 ... # doctest: +ELLIPSIS
1544 **********************************************************************
1545 File ..., line 5, in f
1546 Failed example:
1547 print(2) # first failure
1548 Expected:
1549 200
1550 Got:
1551 2
1552 TestResults(failed=1, attempted=2)
1553
1554For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1555exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001556
1557 >>> def f(x):
1558 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001559 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001560 ... 1
1561 ... >>> raise ValueError(2) # first failure
1562 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001563 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001564 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001565 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001566 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001567 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001568 ... 500
1569 ... '''
1570 >>> test = doctest.DocTestFinder().find(f)[0]
1571 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1572 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1573 ... # doctest: +ELLIPSIS
1574 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001575 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001576 Failed example:
1577 raise ValueError(2) # first failure
1578 Exception raised:
1579 ...
1580 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001581 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001582 >>> flags = doctest.FAIL_FAST
1583 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1584 ... # doctest: +ELLIPSIS
1585 **********************************************************************
1586 File ..., line 5, in f
1587 Failed example:
1588 raise ValueError(2) # first failure
1589 Exception raised:
1590 ...
1591 ValueError: 2
1592 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001593
Thomas Wouters477c8d52006-05-27 19:21:47 +00001594New option flags can also be registered, via register_optionflag(). Here
1595we reach into doctest's internals a bit.
1596
1597 >>> unlikely = "UNLIKELY_OPTION_NAME"
1598 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1599 False
1600 >>> new_flag_value = doctest.register_optionflag(unlikely)
1601 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1602 True
1603
1604Before 2.4.4/2.5, registering a name more than once erroneously created
1605more than one flag value. Here we verify that's fixed:
1606
1607 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1608 >>> redundant_flag_value == new_flag_value
1609 True
1610
1611Clean up.
1612 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1613
Tim Petersc6cbab02004-08-22 19:43:28 +00001614 """
1615
Tim Peters8485b562004-08-04 18:46:34 +00001616 def option_directives(): r"""
1617Tests of `DocTestRunner`'s option directive mechanism.
1618
Edward Loper74bca7a2004-08-12 02:27:44 +00001619Option directives can be used to turn option flags on or off for a
1620single example. To turn an option on for an example, follow that
1621example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001622
1623 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001624 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001625 ... [0, 1, ..., 9]
1626 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001627 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001628 ... [0, 1, ..., 9]
1629 ... '''
1630 >>> test = doctest.DocTestFinder().find(f)[0]
1631 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001632 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001633 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001634 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001635 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001636 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001637 Expected:
1638 [0, 1, ..., 9]
1639 Got:
1640 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001641 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001642
1643To turn an option off for an example, follow that example with a
1644comment of the form ``# doctest: -OPTION``:
1645
1646 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001647 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001648 ... [0, 1, ..., 9]
1649 ...
1650 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001651 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001652 ... [0, 1, ..., 9]
1653 ... '''
1654 >>> test = doctest.DocTestFinder().find(f)[0]
1655 >>> doctest.DocTestRunner(verbose=False,
1656 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001657 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001658 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001659 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001660 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001661 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001662 Expected:
1663 [0, 1, ..., 9]
1664 Got:
1665 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001666 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001667
1668Option directives affect only the example that they appear with; they
1669do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001670
Edward Loper74bca7a2004-08-12 02:27:44 +00001671 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001672 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001673 ... [0, 1, ..., 9]
1674 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001675 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001676 ... [0, 1, ..., 9]
1677 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001678 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001679 ... [0, 1, ..., 9]
1680 ... '''
1681 >>> test = doctest.DocTestFinder().find(f)[0]
1682 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001683 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001684 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001685 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001686 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001687 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001688 Expected:
1689 [0, 1, ..., 9]
1690 Got:
1691 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001692 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001693 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001694 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001695 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001696 Expected:
1697 [0, 1, ..., 9]
1698 Got:
1699 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001700 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001701
Edward Loper74bca7a2004-08-12 02:27:44 +00001702Multiple options may be modified by a single option directive. They
1703may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001704
1705 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001706 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001707 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001708 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001709 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001710 ... [0, 1, ..., 9]
1711 ... '''
1712 >>> test = doctest.DocTestFinder().find(f)[0]
1713 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001714 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001715 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001716 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001717 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001718 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001719 Expected:
1720 [0, 1, ..., 9]
1721 Got:
1722 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001723 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001724
1725 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001726 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001727 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001728 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001729 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1730 ... [0, 1, ..., 9]
1731 ... '''
1732 >>> test = doctest.DocTestFinder().find(f)[0]
1733 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001734 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001735 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001736 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001737 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001738 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001739 Expected:
1740 [0, 1, ..., 9]
1741 Got:
1742 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001743 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001744
1745 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001746 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001747 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001748 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001749 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1750 ... [0, 1, ..., 9]
1751 ... '''
1752 >>> test = doctest.DocTestFinder().find(f)[0]
1753 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001754 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001755 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001756 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001757 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001758 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001759 Expected:
1760 [0, 1, ..., 9]
1761 Got:
1762 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001763 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001764
1765The option directive may be put on the line following the source, as
1766long as a continuation prompt is used:
1767
1768 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001769 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001770 ... ... # doctest: +ELLIPSIS
1771 ... [0, 1, ..., 9]
1772 ... '''
1773 >>> test = doctest.DocTestFinder().find(f)[0]
1774 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001775 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001776
Edward Loper74bca7a2004-08-12 02:27:44 +00001777For examples with multi-line source, the option directive may appear
1778at the end of any line:
1779
1780 >>> def f(x): r'''
1781 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001782 ... ... print(' ', x, end='', sep='')
1783 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001784 ...
1785 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001786 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1787 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001788 ... '''
1789 >>> test = doctest.DocTestFinder().find(f)[0]
1790 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001791 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001792
1793If more than one line of an example with multi-line source has an
1794option directive, then they are combined:
1795
1796 >>> def f(x): r'''
1797 ... Should fail (option directive not on the last line):
1798 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001799 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001800 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001801 ... '''
1802 >>> test = doctest.DocTestFinder().find(f)[0]
1803 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001804 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001805
1806It is an error to have a comment of the form ``# doctest:`` that is
1807*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1808``OPTION`` is an option that has been registered with
1809`register_option`:
1810
1811 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001812 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001813 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1814 Traceback (most recent call last):
1815 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1816
1817 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001818 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001819 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1820 Traceback (most recent call last):
1821 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1822
1823It is an error to use an option directive on a line that contains no
1824source:
1825
1826 >>> s = '>>> # doctest: +ELLIPSIS'
1827 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1828 Traceback (most recent call last):
1829 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 +00001830"""
1831
1832def test_testsource(): r"""
1833Unit tests for `testsource()`.
1834
1835The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001836test with that name in that module, and converts it to a script. The
1837example code is converted to regular Python code. The surrounding
1838words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001839
1840 >>> import test.test_doctest
1841 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001842 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001843 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001844 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001845 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001846 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001847 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001848 #
Edward Lopera5db6002004-08-12 02:41:30 +00001849 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001850 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001851
1852 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001853 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001854 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001855 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001856 ## 1
1857 ## 2
1858 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001859 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001860
1861 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001862 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001863 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001864 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001865 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001866 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001867 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001868 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001869 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001870"""
1871
1872def test_debug(): r"""
1873
1874Create a docstring that we want to debug:
1875
1876 >>> s = '''
1877 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001878 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001879 ... 12
1880 ... '''
1881
1882Create some fake stdin input, to feed to the debugger:
1883
Tim Peters8485b562004-08-04 18:46:34 +00001884 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001885 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001886
1887Run the debugger on the docstring, and then restore sys.stdin.
1888
Edward Loper2de91ba2004-08-27 02:07:46 +00001889 >>> try: doctest.debug_src(s)
1890 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001891 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001892 (Pdb) next
1893 12
Tim Peters8485b562004-08-04 18:46:34 +00001894 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001895 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001896 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001897 12
1898 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001899
1900"""
1901
Brett Cannon31f59292011-02-21 19:29:56 +00001902if not hasattr(sys, 'gettrace') or not sys.gettrace():
1903 def test_pdb_set_trace():
1904 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001905
Brett Cannon31f59292011-02-21 19:29:56 +00001906 You can use pdb.set_trace from a doctest. To do so, you must
1907 retrieve the set_trace function from the pdb module at the time
1908 you use it. The doctest module changes sys.stdout so that it can
1909 capture program output. It also temporarily replaces pdb.set_trace
1910 with a version that restores stdout. This is necessary for you to
1911 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001912
Brett Cannon31f59292011-02-21 19:29:56 +00001913 >>> doc = '''
1914 ... >>> x = 42
1915 ... >>> raise Exception('clé')
1916 ... Traceback (most recent call last):
1917 ... Exception: clé
1918 ... >>> import pdb; pdb.set_trace()
1919 ... '''
1920 >>> parser = doctest.DocTestParser()
1921 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1922 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001923
Brett Cannon31f59292011-02-21 19:29:56 +00001924 To demonstrate this, we'll create a fake standard input that
1925 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001926
Brett Cannon31f59292011-02-21 19:29:56 +00001927 >>> real_stdin = sys.stdin
1928 >>> sys.stdin = _FakeInput([
1929 ... 'print(x)', # print data defined by the example
1930 ... 'continue', # stop debugging
1931 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001932
Brett Cannon31f59292011-02-21 19:29:56 +00001933 >>> try: runner.run(test)
1934 ... finally: sys.stdin = real_stdin
1935 --Return--
1936 > <doctest foo-bar@baz[2]>(1)<module>()->None
1937 -> import pdb; pdb.set_trace()
1938 (Pdb) print(x)
1939 42
1940 (Pdb) continue
1941 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001942
Brett Cannon31f59292011-02-21 19:29:56 +00001943 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001944
Brett Cannon31f59292011-02-21 19:29:56 +00001945 >>> def calls_set_trace():
1946 ... y=2
1947 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001948
Brett Cannon31f59292011-02-21 19:29:56 +00001949 >>> doc = '''
1950 ... >>> x=1
1951 ... >>> calls_set_trace()
1952 ... '''
1953 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1954 >>> real_stdin = sys.stdin
1955 >>> sys.stdin = _FakeInput([
1956 ... 'print(y)', # print data defined in the function
1957 ... 'up', # out of function
1958 ... 'print(x)', # print data defined by the example
1959 ... 'continue', # stop debugging
1960 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001961
Brett Cannon31f59292011-02-21 19:29:56 +00001962 >>> try:
1963 ... runner.run(test)
1964 ... finally:
1965 ... sys.stdin = real_stdin
1966 --Return--
Serhiy Storchakae437a102016-04-24 21:41:02 +03001967 > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
Brett Cannon31f59292011-02-21 19:29:56 +00001968 -> import pdb; pdb.set_trace()
1969 (Pdb) print(y)
1970 2
1971 (Pdb) up
1972 > <doctest foo-bar@baz[1]>(1)<module>()
1973 -> calls_set_trace()
1974 (Pdb) print(x)
1975 1
1976 (Pdb) continue
1977 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001978
Brett Cannon31f59292011-02-21 19:29:56 +00001979 During interactive debugging, source code is shown, even for
1980 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001981
Brett Cannon31f59292011-02-21 19:29:56 +00001982 >>> doc = '''
1983 ... >>> def f(x):
1984 ... ... g(x*2)
1985 ... >>> def g(x):
1986 ... ... print(x+3)
1987 ... ... import pdb; pdb.set_trace()
1988 ... >>> f(3)
1989 ... '''
1990 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1991 >>> real_stdin = sys.stdin
1992 >>> sys.stdin = _FakeInput([
1993 ... 'list', # list source from example 2
1994 ... 'next', # return from g()
1995 ... 'list', # list source from example 1
1996 ... 'next', # return from f()
1997 ... 'list', # list source from example 3
1998 ... 'continue', # stop debugging
1999 ... ''])
2000 >>> try: runner.run(test)
2001 ... finally: sys.stdin = real_stdin
2002 ... # doctest: +NORMALIZE_WHITESPACE
2003 --Return--
2004 > <doctest foo-bar@baz[1]>(3)g()->None
2005 -> import pdb; pdb.set_trace()
2006 (Pdb) list
2007 1 def g(x):
2008 2 print(x+3)
2009 3 -> import pdb; pdb.set_trace()
2010 [EOF]
2011 (Pdb) next
2012 --Return--
2013 > <doctest foo-bar@baz[0]>(2)f()->None
2014 -> g(x*2)
2015 (Pdb) list
2016 1 def f(x):
2017 2 -> g(x*2)
2018 [EOF]
2019 (Pdb) next
2020 --Return--
2021 > <doctest foo-bar@baz[2]>(1)<module>()->None
2022 -> f(3)
2023 (Pdb) list
2024 1 -> f(3)
2025 [EOF]
2026 (Pdb) continue
2027 **********************************************************************
2028 File "foo-bar@baz.py", line 7, in foo-bar@baz
2029 Failed example:
2030 f(3)
2031 Expected nothing
2032 Got:
2033 9
2034 TestResults(failed=1, attempted=3)
2035 """
Jim Fulton356fd192004-08-09 11:34:47 +00002036
Brett Cannon31f59292011-02-21 19:29:56 +00002037 def test_pdb_set_trace_nested():
2038 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00002039
Brett Cannon31f59292011-02-21 19:29:56 +00002040 >>> class C(object):
2041 ... def calls_set_trace(self):
2042 ... y = 1
2043 ... import pdb; pdb.set_trace()
2044 ... self.f1()
2045 ... y = 2
2046 ... def f1(self):
2047 ... x = 1
2048 ... self.f2()
2049 ... x = 2
2050 ... def f2(self):
2051 ... z = 1
2052 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002053
Brett Cannon31f59292011-02-21 19:29:56 +00002054 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002055
Brett Cannon31f59292011-02-21 19:29:56 +00002056 >>> doc = '''
2057 ... >>> a = 1
2058 ... >>> calls_set_trace()
2059 ... '''
2060 >>> parser = doctest.DocTestParser()
2061 >>> runner = doctest.DocTestRunner(verbose=False)
2062 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2063 >>> real_stdin = sys.stdin
2064 >>> sys.stdin = _FakeInput([
2065 ... 'print(y)', # print data defined in the function
2066 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2067 ... 'up', 'print(x)',
2068 ... 'up', 'print(y)',
2069 ... 'up', 'print(foo)',
2070 ... 'continue', # stop debugging
2071 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002072
Brett Cannon31f59292011-02-21 19:29:56 +00002073 >>> try:
2074 ... runner.run(test)
2075 ... finally:
2076 ... sys.stdin = real_stdin
2077 ... # doctest: +REPORT_NDIFF
2078 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2079 -> self.f1()
2080 (Pdb) print(y)
2081 1
2082 (Pdb) step
2083 --Call--
2084 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2085 -> def f1(self):
2086 (Pdb) step
2087 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2088 -> x = 1
2089 (Pdb) step
2090 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2091 -> self.f2()
2092 (Pdb) step
2093 --Call--
2094 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2095 -> def f2(self):
2096 (Pdb) step
2097 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2098 -> z = 1
2099 (Pdb) step
2100 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2101 -> z = 2
2102 (Pdb) print(z)
2103 1
2104 (Pdb) up
2105 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2106 -> self.f2()
2107 (Pdb) print(x)
2108 1
2109 (Pdb) up
2110 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2111 -> self.f1()
2112 (Pdb) print(y)
2113 1
2114 (Pdb) up
2115 > <doctest foo-bar@baz[1]>(1)<module>()
2116 -> calls_set_trace()
2117 (Pdb) print(foo)
2118 *** NameError: name 'foo' is not defined
2119 (Pdb) continue
2120 TestResults(failed=0, attempted=2)
2121 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002122
Tim Peters19397e52004-08-06 22:02:59 +00002123def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002124 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002125
2126 We create a Suite by providing a module. A module can be provided
2127 by passing a module object:
2128
2129 >>> import unittest
2130 >>> import test.sample_doctest
2131 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2132 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002133 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002134
2135 We can also supply the module by name:
2136
2137 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2138 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002139 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002140
R David Murray5abd76a2012-09-10 10:15:58 -04002141 The module need not contain any doctest examples:
2142
2143 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2144 >>> suite.run(unittest.TestResult())
2145 <unittest.result.TestResult run=0 errors=0 failures=0>
2146
R David Murray1976d9b2014-04-14 20:28:36 -04002147 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002148
R David Murray1976d9b2014-04-14 20:28:36 -04002149 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002150 >>> suite.run(unittest.TestResult())
2151 <unittest.result.TestResult run=0 errors=0 failures=0>
2152
Tim Peters19397e52004-08-06 22:02:59 +00002153 We can use the current module:
2154
2155 >>> suite = test.sample_doctest.test_suite()
2156 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002157 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002158
R David Murray1976d9b2014-04-14 20:28:36 -04002159 We can also provide a DocTestFinder:
2160
2161 >>> finder = doctest.DocTestFinder()
2162 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2163 ... test_finder=finder)
2164 >>> suite.run(unittest.TestResult())
2165 <unittest.result.TestResult run=9 errors=0 failures=4>
2166
2167 The DocTestFinder need not return any tests:
2168
2169 >>> finder = doctest.DocTestFinder()
2170 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2171 ... test_finder=finder)
2172 >>> suite.run(unittest.TestResult())
2173 <unittest.result.TestResult run=0 errors=0 failures=0>
2174
Tim Peters19397e52004-08-06 22:02:59 +00002175 We can supply global variables. If we pass globs, they will be
2176 used instead of the module globals. Here we'll pass an empty
2177 globals, triggering an extra error:
2178
2179 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2180 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002181 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002182
2183 Alternatively, we can provide extra globals. Here we'll make an
2184 error go away by providing an extra global variable:
2185
2186 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2187 ... extraglobs={'y': 1})
2188 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002189 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002190
2191 You can pass option flags. Here we'll cause an extra error
2192 by disabling the blank-line feature:
2193
2194 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002195 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002196 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002197 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002198
Tim Peters1e277ee2004-08-07 05:37:52 +00002199 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002200
Jim Fultonf54bad42004-08-28 14:57:56 +00002201 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002202 ... import test.test_doctest
2203 ... test.test_doctest.sillySetup = True
2204
Jim Fultonf54bad42004-08-28 14:57:56 +00002205 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002206 ... import test.test_doctest
2207 ... del test.test_doctest.sillySetup
2208
2209 Here, we installed a silly variable that the test expects:
2210
2211 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2212 ... setUp=setUp, tearDown=tearDown)
2213 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002214 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002215
2216 But the tearDown restores sanity:
2217
2218 >>> import test.test_doctest
2219 >>> test.test_doctest.sillySetup
2220 Traceback (most recent call last):
2221 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002222 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002223
Berker Peksag4882cac2015-04-14 09:30:01 +03002224 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002225 we'll use the setUp function to supply the missing variable y:
2226
2227 >>> def setUp(test):
2228 ... test.globs['y'] = 1
2229
2230 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2231 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002232 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002233
2234 Here, we didn't need to use a tearDown function because we
2235 modified the test globals, which are a copy of the
2236 sample_doctest module dictionary. The test globals are
2237 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002238 """
2239
2240def test_DocFileSuite():
2241 """We can test tests found in text files using a DocFileSuite.
2242
2243 We create a suite by providing the names of one or more text
2244 files that include examples:
2245
2246 >>> import unittest
2247 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002248 ... 'test_doctest2.txt',
2249 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002250 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002251 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002252
2253 The test files are looked for in the directory containing the
2254 calling module. A package keyword argument can be provided to
2255 specify a different relative location.
2256
2257 >>> import unittest
2258 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2259 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002260 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002261 ... package='test')
2262 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002263 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002264
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002265 Support for using a package's __loader__.get_data() is also
2266 provided.
2267
2268 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002269 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002270 >>> if not hasattr(test, '__loader__'):
2271 ... test.__loader__ = pkgutil.get_loader(test)
2272 ... added_loader = True
2273 >>> try:
2274 ... suite = doctest.DocFileSuite('test_doctest.txt',
2275 ... 'test_doctest2.txt',
2276 ... 'test_doctest4.txt',
2277 ... package='test')
2278 ... suite.run(unittest.TestResult())
2279 ... finally:
2280 ... if added_loader:
2281 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002282 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002283
Edward Loper0273f5b2004-09-18 20:27:04 +00002284 '/' should be used as a path separator. It will be converted
2285 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002286
2287 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2288 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002289 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002290
Edward Loper0273f5b2004-09-18 20:27:04 +00002291 If DocFileSuite is used from an interactive session, then files
2292 are resolved relative to the directory of sys.argv[0]:
2293
Christian Heimes45f9af32007-11-27 21:50:00 +00002294 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002295 >>> save_argv = sys.argv
2296 >>> sys.argv = [test.test_doctest.__file__]
2297 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002298 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002299 >>> sys.argv = save_argv
2300
Edward Loper052d0cd2004-09-19 17:19:33 +00002301 By setting `module_relative=False`, os-specific paths may be
2302 used (including absolute paths and paths relative to the
2303 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002304
2305 >>> # Get the absolute path of the test package.
2306 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2307 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2308
2309 >>> # Use it to find the absolute path of test_doctest.txt.
2310 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2311
Edward Loper052d0cd2004-09-19 17:19:33 +00002312 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002313 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002314 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002315
Edward Loper052d0cd2004-09-19 17:19:33 +00002316 It is an error to specify `package` when `module_relative=False`:
2317
2318 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2319 ... package='test')
2320 Traceback (most recent call last):
2321 ValueError: Package may only be specified for module-relative paths.
2322
Tim Peters19397e52004-08-06 22:02:59 +00002323 You can specify initial global variables:
2324
2325 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2326 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002327 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002328 ... globs={'favorite_color': 'blue'})
2329 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002330 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002331
2332 In this case, we supplied a missing favorite color. You can
2333 provide doctest options:
2334
2335 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2336 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002337 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002338 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2339 ... globs={'favorite_color': 'blue'})
2340 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002341 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002342
2343 And, you can provide setUp and tearDown functions:
2344
Jim Fultonf54bad42004-08-28 14:57:56 +00002345 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002346 ... import test.test_doctest
2347 ... test.test_doctest.sillySetup = True
2348
Jim Fultonf54bad42004-08-28 14:57:56 +00002349 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002350 ... import test.test_doctest
2351 ... del test.test_doctest.sillySetup
2352
2353 Here, we installed a silly variable that the test expects:
2354
2355 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2356 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002357 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002358 ... setUp=setUp, tearDown=tearDown)
2359 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002360 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002361
2362 But the tearDown restores sanity:
2363
2364 >>> import test.test_doctest
2365 >>> test.test_doctest.sillySetup
2366 Traceback (most recent call last):
2367 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002368 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002369
Berker Peksag4882cac2015-04-14 09:30:01 +03002370 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002371 Here, we'll use a setUp function to set the favorite color in
2372 test_doctest.txt:
2373
2374 >>> def setUp(test):
2375 ... test.globs['favorite_color'] = 'blue'
2376
2377 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2378 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002379 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002380
2381 Here, we didn't need to use a tearDown function because we
2382 modified the test globals. The test globals are
2383 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002384
Fred Drake7c404a42004-12-21 23:46:34 +00002385 Tests in a file run using `DocFileSuite` can also access the
2386 `__file__` global, which is set to the name of the file
2387 containing the tests:
2388
Benjamin Petersonab078e92016-07-13 21:13:29 -07002389 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
Fred Drake7c404a42004-12-21 23:46:34 +00002390 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002391 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002392
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002393 If the tests contain non-ASCII characters, we have to specify which
2394 encoding the file is encoded with. We do so by using the `encoding`
2395 parameter:
2396
2397 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2398 ... 'test_doctest2.txt',
2399 ... 'test_doctest4.txt',
2400 ... encoding='utf-8')
2401 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002402 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002403
Jim Fultonf54bad42004-08-28 14:57:56 +00002404 """
Tim Peters19397e52004-08-06 22:02:59 +00002405
Jim Fulton07a349c2004-08-22 14:10:00 +00002406def test_trailing_space_in_test():
2407 """
Tim Petersa7def722004-08-23 22:13:22 +00002408 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002409
Jim Fulton07a349c2004-08-22 14:10:00 +00002410 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002411 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002412 foo \n
2413 """
Tim Peters19397e52004-08-06 22:02:59 +00002414
Yury Selivanovb532df62014-12-08 15:00:05 -05002415class Wrapper:
2416 def __init__(self, func):
2417 self.func = func
2418 functools.update_wrapper(self, func)
2419
2420 def __call__(self, *args, **kwargs):
2421 self.func(*args, **kwargs)
2422
2423@Wrapper
2424def test_look_in_unwrapped():
2425 """
2426 Docstrings in wrapped functions must be detected as well.
2427
2428 >>> 'one other test'
2429 'one other test'
2430 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002431
2432def test_unittest_reportflags():
2433 """Default unittest reporting flags can be set to control reporting
2434
2435 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2436 only the first failure of each test. First, we'll look at the
2437 output without the flag. The file test_doctest.txt file has two
2438 tests. They both fail if blank lines are disabled:
2439
2440 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2441 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2442 >>> import unittest
2443 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002444 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002445 Traceback ...
2446 Failed example:
2447 favorite_color
2448 ...
2449 Failed example:
2450 if 1:
2451 ...
2452
2453 Note that we see both failures displayed.
2454
2455 >>> old = doctest.set_unittest_reportflags(
2456 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2457
2458 Now, when we run the test:
2459
2460 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002461 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002462 Traceback ...
2463 Failed example:
2464 favorite_color
2465 Exception raised:
2466 ...
2467 NameError: name 'favorite_color' is not defined
2468 <BLANKLINE>
2469 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002470
Jim Fultonf54bad42004-08-28 14:57:56 +00002471 We get only the first failure.
2472
2473 If we give any reporting options when we set up the tests,
2474 however:
2475
2476 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2477 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2478
2479 Then the default eporting options are ignored:
2480
2481 >>> result = suite.run(unittest.TestResult())
Pablo Galindoc5dc60e2019-01-10 14:29:40 +00002482
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302483 *NOTE*: These doctest are intentionally not placed in raw string to depict
2484 the trailing whitespace using `\x20` in the diff below.
2485
Guido van Rossum7131f842007-02-09 20:13:25 +00002486 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002487 Traceback ...
2488 Failed example:
2489 favorite_color
2490 ...
2491 Failed example:
2492 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002493 print('a')
2494 print()
2495 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002496 Differences (ndiff with -expected +actual):
2497 a
2498 - <BLANKLINE>
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302499 +\x20
Jim Fultonf54bad42004-08-28 14:57:56 +00002500 b
2501 <BLANKLINE>
2502 <BLANKLINE>
2503
2504
2505 Test runners can restore the formatting flags after they run:
2506
2507 >>> ignored = doctest.set_unittest_reportflags(old)
2508
2509 """
2510
Edward Loper052d0cd2004-09-19 17:19:33 +00002511def test_testfile(): r"""
2512Tests for the `testfile()` function. This function runs all the
Min ho Kimc4cacc82019-07-31 08:16:13 +10002513doctest examples in a given file. In its simple invocation, it is
Edward Loper052d0cd2004-09-19 17:19:33 +00002514called with the name of a file, which is taken to be relative to the
2515calling module. The return value is (#failures, #tests).
2516
Florent Xicluna59250852010-02-27 14:21:57 +00002517We don't want `-v` in sys.argv for these tests.
2518
2519 >>> save_argv = sys.argv
2520 >>> if '-v' in sys.argv:
2521 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2522
2523
Edward Loper052d0cd2004-09-19 17:19:33 +00002524 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2525 **********************************************************************
2526 File "...", line 6, in test_doctest.txt
2527 Failed example:
2528 favorite_color
2529 Exception raised:
2530 ...
2531 NameError: name 'favorite_color' is not defined
2532 **********************************************************************
2533 1 items had failures:
2534 1 of 2 in test_doctest.txt
2535 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002536 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002537 >>> doctest.master = None # Reset master.
2538
2539(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002540`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002541same name.)
2542
2543Globals may be specified with the `globs` and `extraglobs` parameters:
2544
2545 >>> globs = {'favorite_color': 'blue'}
2546 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002547 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002548 >>> doctest.master = None # Reset master.
2549
2550 >>> extraglobs = {'favorite_color': 'red'}
2551 >>> doctest.testfile('test_doctest.txt', globs=globs,
2552 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2553 **********************************************************************
2554 File "...", line 6, in test_doctest.txt
2555 Failed example:
2556 favorite_color
2557 Expected:
2558 'blue'
2559 Got:
2560 'red'
2561 **********************************************************************
2562 1 items had failures:
2563 1 of 2 in test_doctest.txt
2564 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002565 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002566 >>> doctest.master = None # Reset master.
2567
2568The file may be made relative to a given module or package, using the
2569optional `module_relative` parameter:
2570
2571 >>> doctest.testfile('test_doctest.txt', globs=globs,
2572 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002573 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002574 >>> doctest.master = None # Reset master.
2575
Ezio Melotti13925002011-03-16 11:05:33 +02002576Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002577
2578 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2579 Trying:
2580 favorite_color
2581 Expecting:
2582 'blue'
2583 ok
2584 Trying:
2585 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002586 print('a')
2587 print()
2588 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002589 Expecting:
2590 a
2591 <BLANKLINE>
2592 b
2593 ok
2594 1 items passed all tests:
2595 2 tests in test_doctest.txt
2596 2 tests in 1 items.
2597 2 passed and 0 failed.
2598 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002599 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002600 >>> doctest.master = None # Reset master.
2601
2602The name of the test may be specified with the optional `name`
2603parameter:
2604
2605 >>> doctest.testfile('test_doctest.txt', name='newname')
2606 ... # doctest: +ELLIPSIS
2607 **********************************************************************
2608 File "...", line 6, in newname
2609 ...
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
Ezio Melotti13925002011-03-16 11:05:33 +02002613The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002614parameter:
2615
2616 >>> doctest.testfile('test_doctest.txt', report=False)
2617 ... # doctest: +ELLIPSIS
2618 **********************************************************************
2619 File "...", line 6, in test_doctest.txt
2620 Failed example:
2621 favorite_color
2622 Exception raised:
2623 ...
2624 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002625 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002626 >>> doctest.master = None # Reset master.
2627
2628The optional keyword argument `raise_on_error` can be used to raise an
2629exception on the first error (which may be useful for postmortem
2630debugging):
2631
2632 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2633 ... # doctest: +ELLIPSIS
2634 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002635 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002636 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002637
2638If the tests contain non-ASCII characters, the tests might fail, since
2639it's unknown which encoding is used. The encoding can be specified
2640using the optional keyword argument `encoding`:
2641
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002642 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002643 **********************************************************************
2644 File "...", line 7, in test_doctest4.txt
2645 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002646 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002647 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002648 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002649 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002650 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002651 **********************************************************************
2652 ...
2653 **********************************************************************
2654 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002655 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002656 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002657 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002658 >>> doctest.master = None # Reset master.
2659
2660 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002661 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002662 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002663
2664Test the verbose output:
2665
2666 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2667 Trying:
2668 'föö'
2669 Expecting:
2670 'f\xf6\xf6'
2671 ok
2672 Trying:
2673 'bÄ…r'
2674 Expecting:
2675 'b\u0105r'
2676 ok
2677 1 items passed all tests:
2678 2 tests in test_doctest4.txt
2679 2 tests in 1 items.
2680 2 passed and 0 failed.
2681 Test passed.
2682 TestResults(failed=0, attempted=2)
2683 >>> doctest.master = None # Reset master.
2684 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002685"""
2686
Peter Donise0b81012020-03-26 11:53:16 -04002687class TestImporter(importlib.abc.MetaPathFinder, importlib.abc.ResourceLoader):
2688
2689 def find_spec(self, fullname, path, target=None):
2690 return importlib.util.spec_from_file_location(fullname, path, loader=self)
2691
2692 def get_data(self, path):
2693 with open(path, mode='rb') as f:
2694 return f.read()
2695
2696class TestHook:
2697
2698 def __init__(self, pathdir):
2699 self.sys_path = sys.path[:]
2700 self.meta_path = sys.meta_path[:]
2701 self.path_hooks = sys.path_hooks[:]
2702 sys.path.append(pathdir)
2703 sys.path_importer_cache.clear()
2704 self.modules_before = sys.modules.copy()
2705 self.importer = TestImporter()
2706 sys.meta_path.append(self.importer)
2707
2708 def remove(self):
2709 sys.path[:] = self.sys_path
2710 sys.meta_path[:] = self.meta_path
2711 sys.path_hooks[:] = self.path_hooks
2712 sys.path_importer_cache.clear()
2713 sys.modules.clear()
2714 sys.modules.update(self.modules_before)
2715
2716
2717@contextlib.contextmanager
2718def test_hook(pathdir):
2719 hook = TestHook(pathdir)
2720 try:
2721 yield hook
2722 finally:
2723 hook.remove()
2724
2725
R David Murrayb48cb292014-10-02 22:42:42 -04002726def test_lineendings(): r"""
Peter Donise0b81012020-03-26 11:53:16 -04002727*nix systems use \n line endings, while Windows systems use \r\n, and
2728old Mac systems used \r, which Python still recognizes as a line ending. Python
R David Murrayb48cb292014-10-02 22:42:42 -04002729handles this using universal newline mode for reading files. Let's make
2730sure doctest does so (issue 8473) by creating temporary test files using each
Peter Donise0b81012020-03-26 11:53:16 -04002731of the three line disciplines. At least one will not match either the universal
2732newline \n or os.linesep for the platform the test is run on.
R David Murrayb48cb292014-10-02 22:42:42 -04002733
2734Windows line endings first:
2735
2736 >>> import tempfile, os
2737 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002738 >>> with open(fn, 'wb') as f:
2739 ... 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 -04002740 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002741 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002742 TestResults(failed=0, attempted=1)
2743 >>> os.remove(fn)
2744
2745And now *nix line endings:
2746
2747 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002748 >>> with open(fn, 'wb') as f:
2749 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002750 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002751 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002752 TestResults(failed=0, attempted=1)
2753 >>> os.remove(fn)
2754
Peter Donise0b81012020-03-26 11:53:16 -04002755And finally old Mac line endings:
2756
2757 >>> fn = tempfile.mktemp()
2758 >>> with open(fn, 'wb') as f:
2759 ... f.write(b'Test:\r\r >>> x = 1 + 1\r\rDone.\r')
2760 30
2761 >>> doctest.testfile(fn, module_relative=False, verbose=False)
2762 TestResults(failed=0, attempted=1)
2763 >>> os.remove(fn)
2764
2765Now we test with a package loader that has a get_data method, since that
2766bypasses the standard universal newline handling so doctest has to do the
2767newline conversion itself; let's make sure it does so correctly (issue 1812).
2768We'll write a file inside the package that has all three kinds of line endings
2769in it, and use a package hook to install a custom loader; on any platform,
2770at least one of the line endings will raise a ValueError for inconsistent
2771whitespace if doctest does not correctly do the newline conversion.
2772
2773 >>> dn = tempfile.mkdtemp()
2774 >>> pkg = os.path.join(dn, "doctest_testpkg")
2775 >>> os.mkdir(pkg)
Hai Shi46605972020-08-04 00:49:18 +08002776 >>> os_helper.create_empty_file(os.path.join(pkg, "__init__.py"))
Peter Donise0b81012020-03-26 11:53:16 -04002777 >>> fn = os.path.join(pkg, "doctest_testfile.txt")
2778 >>> with open(fn, 'wb') as f:
2779 ... f.write(
2780 ... b'Test:\r\n\r\n'
2781 ... b' >>> x = 1 + 1\r\n\r\n'
2782 ... b'Done.\r\n'
2783 ... b'Test:\n\n'
2784 ... b' >>> x = 1 + 1\n\n'
2785 ... b'Done.\n'
2786 ... b'Test:\r\r'
2787 ... b' >>> x = 1 + 1\r\r'
2788 ... b'Done.\r'
2789 ... )
2790 95
2791 >>> with test_hook(dn):
2792 ... doctest.testfile("doctest_testfile.txt", package="doctest_testpkg", verbose=False)
2793 TestResults(failed=0, attempted=3)
2794 >>> shutil.rmtree(dn)
2795
R David Murrayb48cb292014-10-02 22:42:42 -04002796"""
2797
R. David Murray58641de2009-06-12 15:33:19 +00002798def test_testmod(): r"""
2799Tests for the testmod function. More might be useful, but for now we're just
2800testing the case raised by Issue 6195, where trying to doctest a C module would
2801fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2802out of the binary module.
2803
2804 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002805 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002806 TestResults(failed=0, attempted=0)
2807"""
2808
Victor Stinner9d396392010-10-16 21:54:59 +00002809try:
2810 os.fsencode("foo-bär@baz.py")
2811except UnicodeEncodeError:
2812 # Skip the test: the filesystem encoding is unable to encode the filename
2813 pass
2814else:
2815 def test_unicode(): """
2816Check doctest with a non-ascii filename:
2817
2818 >>> doc = '''
2819 ... >>> raise Exception('clé')
2820 ... '''
2821 ...
2822 >>> parser = doctest.DocTestParser()
2823 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2824 >>> test
2825 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2826 >>> runner = doctest.DocTestRunner(verbose=False)
2827 >>> runner.run(test) # doctest: +ELLIPSIS
2828 **********************************************************************
2829 File "foo-bär@baz.py", line 2, in foo-bär@baz
2830 Failed example:
2831 raise Exception('clé')
2832 Exception raised:
2833 Traceback (most recent call last):
2834 File ...
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03002835 exec(compile(example.source, filename, "single",
Victor Stinner9d396392010-10-16 21:54:59 +00002836 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2837 raise Exception('clé')
2838 Exception: clé
2839 TestResults(failed=1, attempted=1)
2840 """
2841
R David Murray5707d502013-06-23 14:24:13 -04002842def test_CLI(): r"""
2843The doctest module can be used to run doctests against an arbitrary file.
2844These tests test this CLI functionality.
2845
2846We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002847to a temp dir to run the command against. Due to a current limitation in
2848script_helpers, though, we need a little utility function to turn the returned
2849output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002850
R David Murray4af68982013-06-25 08:11:22 -04002851 >>> def normalize(s):
2852 ... return '\n'.join(s.decode().splitlines())
2853
R David Murray4af68982013-06-25 08:11:22 -04002854With those preliminaries out of the way, we'll start with a file with two
2855simple tests and no errors. We'll run both the unadorned doctest command, and
2856the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002857
Hai Shi46605972020-08-04 00:49:18 +08002858 >>> from test.support import script_helper
2859 >>> from test.support.os_helper import temp_dir
Berker Peksagce643912015-05-06 06:33:17 +03002860 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002861 ... fn = os.path.join(tmpdir, 'myfile.doc')
Inada Naoki8bbfeb32021-04-02 12:53:46 +09002862 ... with open(fn, 'w', encoding='utf-8') as f:
R David Murray5707d502013-06-23 14:24:13 -04002863 ... _ = f.write('This is a very simple test file.\n')
2864 ... _ = f.write(' >>> 1 + 1\n')
2865 ... _ = f.write(' 2\n')
2866 ... _ = f.write(' >>> "a"\n')
2867 ... _ = f.write(" 'a'\n")
2868 ... _ = f.write('\n')
2869 ... _ = f.write('And that is it.\n')
2870 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002871 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002872 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002873 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002874
2875With no arguments and passing tests, we should get no output:
2876
2877 >>> rc1, out1, err1
2878 (0, b'', b'')
2879
2880With the verbose flag, we should see the test output, but no error output:
2881
2882 >>> rc2, err2
2883 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002884 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002885 Trying:
2886 1 + 1
2887 Expecting:
2888 2
2889 ok
2890 Trying:
2891 "a"
2892 Expecting:
2893 'a'
2894 ok
2895 1 items passed all tests:
2896 2 tests in myfile.doc
2897 2 tests in 1 items.
2898 2 passed and 0 failed.
2899 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002900
2901Now we'll write a couple files, one with three tests, the other a python module
2902with two tests, both of the files having "errors" in the tests that can be made
2903non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2904the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002905allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002906ability to process more than one file on the command line and, since the second
2907file ends in '.py', its handling of python module files (as opposed to straight
2908text files).
2909
Hai Shi46605972020-08-04 00:49:18 +08002910 >>> from test.support import script_helper
2911 >>> from test.support.os_helper import temp_dir
Berker Peksagce643912015-05-06 06:33:17 +03002912 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002913 ... fn = os.path.join(tmpdir, 'myfile.doc')
Inada Naoki8bbfeb32021-04-02 12:53:46 +09002914 ... with open(fn, 'w', encoding="utf-8") as f:
R David Murray5707d502013-06-23 14:24:13 -04002915 ... _ = f.write('This is another simple test file.\n')
2916 ... _ = f.write(' >>> 1 + 1\n')
2917 ... _ = f.write(' 2\n')
2918 ... _ = f.write(' >>> "abcdef"\n')
2919 ... _ = f.write(" 'a...f'\n")
2920 ... _ = f.write(' >>> "ajkml"\n')
2921 ... _ = f.write(" 'a...l'\n")
2922 ... _ = f.write('\n')
2923 ... _ = f.write('And that is it.\n')
2924 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
Inada Naoki8bbfeb32021-04-02 12:53:46 +09002925 ... with open(fn2, 'w', encoding='utf-8') as f:
R David Murray5707d502013-06-23 14:24:13 -04002926 ... _ = f.write('def test_func():\n')
2927 ... _ = f.write(' \"\"\"\n')
2928 ... _ = f.write(' This is simple python test function.\n')
2929 ... _ = f.write(' >>> 1 + 1\n')
2930 ... _ = f.write(' 2\n')
2931 ... _ = f.write(' >>> "abc def"\n')
2932 ... _ = f.write(" 'abc def'\n")
2933 ... _ = f.write("\n")
2934 ... _ = f.write(' \"\"\"\n')
R David Murray5707d502013-06-23 14:24:13 -04002935 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002936 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002937 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002938 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002939 ... rc3, out3, err3 = script_helper.assert_python_ok(
2940 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002941 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002942 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002943 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002944 ... rc5, out5, err5 = script_helper.assert_python_ok(
2945 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002946 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002947
2948Our first test run will show the errors from the first file (doctest stops if a
2949file has errors). Note that doctest test-run error output appears on stdout,
2950not stderr:
2951
2952 >>> rc1, err1
2953 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002954 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002955 **********************************************************************
2956 File "...myfile.doc", line 4, in myfile.doc
2957 Failed example:
2958 "abcdef"
2959 Expected:
2960 'a...f'
2961 Got:
2962 'abcdef'
2963 **********************************************************************
2964 File "...myfile.doc", line 6, in myfile.doc
2965 Failed example:
2966 "ajkml"
2967 Expected:
2968 'a...l'
2969 Got:
2970 'ajkml'
2971 **********************************************************************
2972 1 items had failures:
2973 2 of 3 in myfile.doc
2974 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002975
2976With -o ELLIPSIS specified, the second run, against just the first file, should
2977produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2978should the third, which ran against both files:
2979
2980 >>> rc2, out2, err2
2981 (0, b'', b'')
2982 >>> rc3, out3, err3
2983 (0, b'', b'')
2984
2985The fourth run uses FAIL_FAST, so we should see only one error:
2986
2987 >>> rc4, err4
2988 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002989 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002990 **********************************************************************
2991 File "...myfile.doc", line 4, in myfile.doc
2992 Failed example:
2993 "abcdef"
2994 Expected:
2995 'a...f'
2996 Got:
2997 'abcdef'
2998 **********************************************************************
2999 1 items had failures:
3000 1 of 2 in myfile.doc
3001 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04003002
3003The fifth test uses verbose with the two options, so we should get verbose
3004success output for the tests in both files:
3005
3006 >>> rc5, err5
3007 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04003008 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04003009 Trying:
3010 1 + 1
3011 Expecting:
3012 2
3013 ok
3014 Trying:
3015 "abcdef"
3016 Expecting:
3017 'a...f'
3018 ok
3019 Trying:
3020 "ajkml"
3021 Expecting:
3022 'a...l'
3023 ok
3024 1 items passed all tests:
3025 3 tests in myfile.doc
3026 3 tests in 1 items.
3027 3 passed and 0 failed.
3028 Test passed.
3029 Trying:
3030 1 + 1
3031 Expecting:
3032 2
3033 ok
3034 Trying:
3035 "abc def"
3036 Expecting:
3037 'abc def'
3038 ok
3039 1 items had no tests:
3040 myfile2
3041 1 items passed all tests:
3042 2 tests in myfile2.test_func
3043 2 tests in 2 items.
3044 2 passed and 0 failed.
3045 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04003046
3047We should also check some typical error cases.
3048
3049Invalid file name:
3050
3051 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03003052 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04003053 >>> rc, out
3054 (1, b'')
pxinwr8d4f57d2020-12-05 04:19:32 +08003055 >>> # The exact error message changes depending on the platform.
R David Murray4af68982013-06-25 08:11:22 -04003056 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003057 Traceback (most recent call last):
3058 ...
pxinwr8d4f57d2020-12-05 04:19:32 +08003059 FileNotFoundError: [Errno ...] ...nosuchfile...
R David Murray5707d502013-06-23 14:24:13 -04003060
3061Invalid doctest option:
3062
3063 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03003064 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04003065 >>> rc, out
3066 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04003067 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003068 usage...invalid...nosuchoption...
3069
3070"""
3071
Sanyam Khuranacbb16452019-01-09 19:08:38 +05303072def test_no_trailing_whitespace_stripping():
3073 r"""
3074 The fancy reports had a bug for a long time where any trailing whitespace on
3075 the reported diff lines was stripped, making it impossible to see the
3076 differences in line reported as different that differed only in the amount of
3077 trailing whitespace. The whitespace still isn't particularly visible unless
3078 you use NDIFF, but at least it is now there to be found.
3079
3080 *NOTE*: This snippet was intentionally put inside a raw string to get rid of
3081 leading whitespace error in executing the example below
3082
3083 >>> def f(x):
3084 ... r'''
3085 ... >>> print('\n'.join(['a ', 'b']))
3086 ... a
3087 ... b
3088 ... '''
3089 """
3090 """
3091 *NOTE*: These doctest are not placed in raw string to depict the trailing whitespace
3092 using `\x20`
3093
3094 >>> test = doctest.DocTestFinder().find(f)[0]
3095 >>> flags = doctest.REPORT_NDIFF
3096 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
3097 ... # doctest: +ELLIPSIS
3098 **********************************************************************
3099 File ..., line 3, in f
3100 Failed example:
3101 print('\n'.join(['a ', 'b']))
3102 Differences (ndiff with -expected +actual):
3103 - a
3104 + a
3105 b
3106 TestResults(failed=1, attempted=1)
3107
3108 *NOTE*: `\x20` is for checking the trailing whitespace on the +a line above.
3109 We cannot use actual spaces there, as a commit hook prevents from committing
3110 patches that contain trailing whitespace. More info on Issue 24746.
3111 """
3112
Tim Peters8485b562004-08-04 18:46:34 +00003113
Miss Islington (bot)65de8082021-10-20 09:52:22 -07003114def load_tests(loader, tests, pattern):
3115 tests.addTest(doctest.DocTestSuite(doctest))
3116 tests.addTest(doctest.DocTestSuite())
3117 return tests
Jason R. Coombsb9650a02018-03-05 18:29:08 -05003118
3119
Tim Peters8485b562004-08-04 18:46:34 +00003120def test_coverage(coverdir):
Hai Shi46605972020-08-04 00:49:18 +08003121 trace = import_helper.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01003122 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00003123 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00003124 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00003125 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003126 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00003127 r.write_results(show_missing=True, summary=True,
3128 coverdir=coverdir)
3129
Miss Islington (bot)65de8082021-10-20 09:52:22 -07003130
Tim Peters8485b562004-08-04 18:46:34 +00003131if __name__ == '__main__':
3132 if '-c' in sys.argv:
3133 test_coverage('/tmp/doctest.cover')
3134 else:
Miss Islington (bot)65de8082021-10-20 09:52:22 -07003135 unittest.main()