blob: 9703f871ad640c38761ba3c1d931894614380886 [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
Miss Islington (bot)1f45cc02021-10-28 01:09:41 -070099 a_class_attribute = 42
100
101 @classmethod
102 @property
103 def a_classmethod_property(cls):
104 """
105 >>> print(SampleClass.a_classmethod_property)
106 42
107 """
108 return cls.a_class_attribute
109
Tim Peters8485b562004-08-04 18:46:34 +0000110 class NestedClass:
111 """
112 >>> x = SampleClass.NestedClass(5)
113 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +0000114 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +0000115 25
116 """
117 def __init__(self, val=0):
118 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000119 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +0000120 0
121 """
122 self.val = val
123 def square(self):
124 return SampleClass.NestedClass(self.val*self.val)
125 def get(self):
126 return self.val
127
128class SampleNewStyleClass(object):
129 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000130 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000131 1
132 2
133 3
134 """
135 def __init__(self, val):
136 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000137 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000138 12
139 """
140 self.val = val
141
142 def double(self):
143 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000144 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000145 24
146 """
147 return SampleNewStyleClass(self.val + self.val)
148
149 def get(self):
150 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000151 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000152 -5
153 """
154 return self.val
155
156######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000157## Fake stdin (for testing interactive debugging)
158######################################################################
159
160class _FakeInput:
161 """
162 A fake input stream for pdb's interactive debugger. Whenever a
163 line is read, print it (to simulate the user typing it), and then
164 return it. The set of lines to return is specified in the
165 constructor; they should not have trailing newlines.
166 """
167 def __init__(self, lines):
168 self.lines = lines
169
170 def readline(self):
171 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000172 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000173 return line+'\n'
174
175######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000176## Test Cases
177######################################################################
178
179def test_Example(): r"""
180Unit tests for the `Example` class.
181
Edward Lopera6b68322004-08-26 00:05:43 +0000182Example is a simple container class that holds:
183 - `source`: A source string.
184 - `want`: An expected output string.
185 - `exc_msg`: An expected exception message string (or None if no
186 exception is expected).
187 - `lineno`: A line number (within the docstring).
188 - `indent`: The example's indentation in the input string.
189 - `options`: An option dictionary, mapping option flags to True or
190 False.
Tim Peters8485b562004-08-04 18:46:34 +0000191
Edward Lopera6b68322004-08-26 00:05:43 +0000192These attributes are set by the constructor. `source` and `want` are
193required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000194
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000195 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000196 >>> (example.source, example.want, example.exc_msg,
197 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000198 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000199
200The first three attributes (`source`, `want`, and `exc_msg`) may be
201specified positionally; the remaining arguments should be specified as
202keyword arguments:
203
204 >>> exc_msg = 'IndexError: pop from an empty list'
205 >>> example = doctest.Example('[].pop()', '', exc_msg,
206 ... lineno=5, indent=4,
207 ... options={doctest.ELLIPSIS: True})
208 >>> (example.source, example.want, example.exc_msg,
209 ... example.lineno, example.indent, example.options)
210 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
211
212The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000213
Tim Petersbb431472004-08-09 03:51:46 +0000214 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000215 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000216 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000217 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000218
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000219 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000220 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000221 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000222
Tim Petersbb431472004-08-09 03:51:46 +0000223 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000224 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000225 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000226 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000227
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000228 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000229 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000230 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000231
Edward Lopera6b68322004-08-26 00:05:43 +0000232 Empty source string (which should never appear in real examples)
233 >>> e = doctest.Example('', '')
234 >>> e.source, e.want
235 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000236
Edward Lopera6b68322004-08-26 00:05:43 +0000237The constructor normalizes the `want` string to end in a newline,
238unless it's the empty string:
239
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000240 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000241 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000242 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000243
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000244 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000245 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000246 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000247
Edward Lopera6b68322004-08-26 00:05:43 +0000248 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000249 >>> e.source, e.want
250 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000251
252The constructor normalizes the `exc_msg` string to end in a newline,
253unless it's `None`:
254
255 Message spans one line
256 >>> exc_msg = 'IndexError: pop from an empty list'
257 >>> e = doctest.Example('[].pop()', '', exc_msg)
258 >>> e.exc_msg
259 'IndexError: pop from an empty list\n'
260
261 >>> exc_msg = 'IndexError: pop from an empty list\n'
262 >>> e = doctest.Example('[].pop()', '', exc_msg)
263 >>> e.exc_msg
264 'IndexError: pop from an empty list\n'
265
266 Message spans multiple lines
267 >>> exc_msg = 'ValueError: 1\n 2'
268 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
269 >>> e.exc_msg
270 'ValueError: 1\n 2\n'
271
272 >>> exc_msg = 'ValueError: 1\n 2\n'
273 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
274 >>> e.exc_msg
275 'ValueError: 1\n 2\n'
276
277 Empty (but non-None) exception message (which should never appear
278 in real examples)
279 >>> exc_msg = ''
280 >>> e = doctest.Example('raise X()', '', exc_msg)
281 >>> e.exc_msg
282 '\n'
Antoine Pitrou165b1282011-12-18 20:20:17 +0100283
284Compare `Example`:
285 >>> example = doctest.Example('print 1', '1\n')
286 >>> same_example = doctest.Example('print 1', '1\n')
287 >>> other_example = doctest.Example('print 42', '42\n')
288 >>> example == same_example
289 True
290 >>> example != same_example
291 False
292 >>> hash(example) == hash(same_example)
293 True
294 >>> example == other_example
295 False
296 >>> example != other_example
297 True
Tim Peters8485b562004-08-04 18:46:34 +0000298"""
299
300def test_DocTest(): r"""
301Unit tests for the `DocTest` class.
302
303DocTest is a collection of examples, extracted from a docstring, along
304with information about where the docstring comes from (a name,
305filename, and line number). The docstring is parsed by the `DocTest`
306constructor:
307
308 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000309 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000310 ... 12
311 ...
312 ... Non-example text.
313 ...
R David Murray44b548d2016-09-08 13:59:53 -0400314 ... >>> print('another\\example')
Tim Peters8485b562004-08-04 18:46:34 +0000315 ... another
316 ... example
317 ... '''
318 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000319 >>> parser = doctest.DocTestParser()
320 >>> test = parser.get_doctest(docstring, globs, 'some_test',
321 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000322 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000323 <DocTest some_test from some_file:20 (2 examples)>
324 >>> len(test.examples)
325 2
326 >>> e1, e2 = test.examples
327 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000328 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000329 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000330 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000331
332Source information (name, filename, and line number) is available as
333attributes on the doctest object:
334
335 >>> (test.name, test.filename, test.lineno)
336 ('some_test', 'some_file', 20)
337
338The line number of an example within its containing file is found by
339adding the line number of the example and the line number of its
340containing test:
341
342 >>> test.lineno + e1.lineno
343 21
344 >>> test.lineno + e2.lineno
345 26
346
Martin Panter46f50722016-05-26 05:35:26 +0000347If the docstring contains inconsistent leading whitespace in the
Tim Peters8485b562004-08-04 18:46:34 +0000348expected output of an example, then `DocTest` will raise a ValueError:
349
350 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000351 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000352 ... bad
353 ... indentation
354 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000355 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000356 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000357 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000358
359If the docstring contains inconsistent leading whitespace on
360continuation lines, then `DocTest` will raise a ValueError:
361
362 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000363 ... >>> print(('bad indentation',
364 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000365 ... ('bad', 'indentation')
366 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000367 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000368 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000369 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000370
371If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
372will raise a ValueError:
373
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000374 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000375 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000376 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000377 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000378
379If there's no blank space after a PS2 prompt ('...'), then `DocTest`
380will raise a ValueError:
381
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000382 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000383 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000384 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000385 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000386
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100387Compare `DocTest`:
388
389 >>> docstring = '''
390 ... >>> print 12
391 ... 12
392 ... '''
393 >>> test = parser.get_doctest(docstring, globs, 'some_test',
394 ... 'some_test', 20)
395 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
396 ... 'some_test', 20)
397 >>> test == same_test
398 True
399 >>> test != same_test
400 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100401 >>> hash(test) == hash(same_test)
402 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100403 >>> docstring = '''
404 ... >>> print 42
405 ... 42
406 ... '''
407 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
408 ... 'other_file', 10)
409 >>> test == other_test
410 False
411 >>> test != other_test
412 True
413
414Compare `DocTestCase`:
415
416 >>> DocTestCase = doctest.DocTestCase
417 >>> test_case = DocTestCase(test)
418 >>> same_test_case = DocTestCase(same_test)
419 >>> other_test_case = DocTestCase(other_test)
420 >>> test_case == same_test_case
421 True
422 >>> test_case != same_test_case
423 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100424 >>> hash(test_case) == hash(same_test_case)
425 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100426 >>> test == other_test_case
427 False
428 >>> test != other_test_case
429 True
430
Tim Peters8485b562004-08-04 18:46:34 +0000431"""
432
Zachary Ware7119b452013-11-24 02:21:57 -0600433class test_DocTestFinder:
434 def basics(): r"""
Tim Peters8485b562004-08-04 18:46:34 +0000435Unit tests for the `DocTestFinder` class.
436
437DocTestFinder is used to extract DocTests from an object's docstring
438and the docstrings of its contained objects. It can be used with
439modules, functions, classes, methods, staticmethods, classmethods, and
440properties.
441
442Finding Tests in Functions
443~~~~~~~~~~~~~~~~~~~~~~~~~~
444For a function whose docstring contains examples, DocTestFinder.find()
445will return a single test (for that function's docstring):
446
Tim Peters8485b562004-08-04 18:46:34 +0000447 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000448
449We'll simulate a __file__ attr that ends in pyc:
450
451 >>> import test.test_doctest
452 >>> old = test.test_doctest.__file__
453 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
454
Tim Peters8485b562004-08-04 18:46:34 +0000455 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000456
Guido van Rossum7131f842007-02-09 20:13:25 +0000457 >>> print(tests) # doctest: +ELLIPSIS
Miss Islington (bot)10d6f6b2021-05-05 11:01:21 -0700458 [<DocTest sample_func from test_doctest.py:28 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000459
Tim Peters4de7c5c2004-08-23 22:38:05 +0000460The exact name depends on how test_doctest was invoked, so allow for
461leading path components.
462
463 >>> tests[0].filename # doctest: +ELLIPSIS
464 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000465
466 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000467
Jim Fulton07a349c2004-08-22 14:10:00 +0000468
Tim Peters8485b562004-08-04 18:46:34 +0000469 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000470 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000471 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000472
Edward Loper32ddbf72004-09-13 05:47:24 +0000473By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000474
475 >>> def no_docstring(v):
476 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000477 >>> finder.find(no_docstring)
478 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000479
480However, the optional argument `exclude_empty` to the DocTestFinder
481constructor can be used to exclude tests for objects with empty
482docstrings:
483
484 >>> def no_docstring(v):
485 ... pass
486 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
487 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000488 []
489
490If the function has a docstring with no examples, then a test with no
491examples is returned. (This lets `DocTestRunner` collect statistics
492about which functions have no tests -- but is that useful? And should
493an empty test also be created when there's no docstring?)
494
495 >>> def no_examples(v):
496 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000497 >>> finder.find(no_examples) # doctest: +ELLIPSIS
498 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000499
500Finding Tests in Classes
501~~~~~~~~~~~~~~~~~~~~~~~~
502For a class, DocTestFinder will create a test for the class's
503docstring, and will recursively explore its contents, including
504methods, classmethods, staticmethods, properties, and nested classes.
505
506 >>> finder = doctest.DocTestFinder()
507 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000508 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000509 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000510 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000511 3 SampleClass.NestedClass
512 1 SampleClass.NestedClass.__init__
513 1 SampleClass.__init__
514 2 SampleClass.a_classmethod
Miss Islington (bot)1f45cc02021-10-28 01:09:41 -0700515 1 SampleClass.a_classmethod_property
Tim Peters8485b562004-08-04 18:46:34 +0000516 1 SampleClass.a_property
517 1 SampleClass.a_staticmethod
518 1 SampleClass.double
519 1 SampleClass.get
520
521New-style classes are also supported:
522
523 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000524 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000525 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000526 1 SampleNewStyleClass
527 1 SampleNewStyleClass.__init__
528 1 SampleNewStyleClass.double
529 1 SampleNewStyleClass.get
530
531Finding Tests in Modules
532~~~~~~~~~~~~~~~~~~~~~~~~
533For a module, DocTestFinder will create a test for the class's
534docstring, and will recursively explore its contents, including
535functions, classes, and the `__test__` dictionary, if it exists:
536
537 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000538 >>> import types
539 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000540 >>> def triple(val):
541 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000542 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000543 ... 33
544 ... '''
545 ... return val*3
546 >>> m.__dict__.update({
547 ... 'sample_func': sample_func,
548 ... 'SampleClass': SampleClass,
549 ... '__doc__': '''
550 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000551 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000552 ... module
553 ... ''',
554 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000555 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000556 ... 'c': triple}})
557
558 >>> finder = doctest.DocTestFinder()
559 >>> # Use module=test.test_doctest, to prevent doctest from
560 >>> # ignoring the objects since they weren't defined in m.
561 >>> import test.test_doctest
562 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000563 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000564 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000565 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000566 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000567 3 some_module.SampleClass.NestedClass
568 1 some_module.SampleClass.NestedClass.__init__
569 1 some_module.SampleClass.__init__
570 2 some_module.SampleClass.a_classmethod
Miss Islington (bot)1f45cc02021-10-28 01:09:41 -0700571 1 some_module.SampleClass.a_classmethod_property
Tim Peters8485b562004-08-04 18:46:34 +0000572 1 some_module.SampleClass.a_property
573 1 some_module.SampleClass.a_staticmethod
574 1 some_module.SampleClass.double
575 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000576 1 some_module.__test__.c
577 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000578 1 some_module.sample_func
579
580Duplicate Removal
581~~~~~~~~~~~~~~~~~
582If a single object is listed twice (under different names), then tests
583will only be generated for it once:
584
Tim Petersf3f57472004-08-08 06:11:48 +0000585 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000586 >>> assert doctest_aliases.TwoNames.f
587 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000588 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000589 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000590 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000591 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000592 test.doctest_aliases.TwoNames
593
594 TwoNames.f and TwoNames.g are bound to the same object.
595 We can't guess which will be found in doctest's traversal of
596 TwoNames.__dict__ first, so we have to allow for either.
597
598 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000599 True
600
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000601Empty Tests
602~~~~~~~~~~~
603By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000604
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000605 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000606 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000607 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000608 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000609 3 SampleClass.NestedClass
610 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000611 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000612 2 SampleClass.a_classmethod
Miss Islington (bot)1f45cc02021-10-28 01:09:41 -0700613 1 SampleClass.a_classmethod_property
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000614 1 SampleClass.a_property
615 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000616 1 SampleClass.double
617 1 SampleClass.get
618
619By default, that excluded objects with no doctests. exclude_empty=False
620tells it to include (empty) tests for objects with no doctests. This feature
621is really to support backward compatibility in what doctest.master.summarize()
622displays.
623
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000624 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000625 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000626 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000627 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000628 3 SampleClass.NestedClass
629 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000630 0 SampleClass.NestedClass.get
631 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000632 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000633 2 SampleClass.a_classmethod
Miss Islington (bot)1f45cc02021-10-28 01:09:41 -0700634 1 SampleClass.a_classmethod_property
Tim Peters8485b562004-08-04 18:46:34 +0000635 1 SampleClass.a_property
636 1 SampleClass.a_staticmethod
637 1 SampleClass.double
638 1 SampleClass.get
639
Tim Peters8485b562004-08-04 18:46:34 +0000640Turning off Recursion
641~~~~~~~~~~~~~~~~~~~~~
642DocTestFinder can be told not to look for tests in contained objects
643using the `recurse` flag:
644
645 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000646 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000647 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000648 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000649
650Line numbers
651~~~~~~~~~~~~
652DocTestFinder finds the line number of each example:
653
654 >>> def f(x):
655 ... '''
656 ... >>> x = 12
657 ...
658 ... some text
659 ...
660 ... >>> # examples are not created for comments & bare prompts.
661 ... >>>
662 ... ...
663 ...
664 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000665 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000666 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000667 ... >>> x//2
668 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000669 ... '''
670 >>> test = doctest.DocTestFinder().find(f)[0]
671 >>> [e.lineno for e in test.examples]
672 [1, 9, 12]
Zachary Ware7119b452013-11-24 02:21:57 -0600673"""
674
675 if int.__doc__: # simple check for --without-doc-strings, skip if lacking
676 def non_Python_modules(): r"""
Zachary Warea4b7a752013-11-24 01:19:09 -0600677
678Finding Doctests in Modules Not Written in Python
679~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
680DocTestFinder can also find doctests in most modules not written in Python.
681We'll use builtins as an example, since it almost certainly isn't written in
682plain ol' Python and is guaranteed to be available.
683
684 >>> import builtins
685 >>> tests = doctest.DocTestFinder().find(builtins)
sweeneydea81849b2020-04-22 17:05:48 -0400686 >>> 816 < len(tests) < 836 # approximate number of objects with docstrings
Zachary Ware7119b452013-11-24 02:21:57 -0600687 True
Zachary Warea4b7a752013-11-24 01:19:09 -0600688 >>> real_tests = [t for t in tests if len(t.examples) > 0]
Zachary Ware7119b452013-11-24 02:21:57 -0600689 >>> len(real_tests) # objects that actually have doctests
Niklas Fiekas8bd216d2020-05-29 18:28:02 +0200690 14
Zachary Warea4b7a752013-11-24 01:19:09 -0600691 >>> for t in real_tests:
692 ... print('{} {}'.format(len(t.examples), t.name))
693 ...
694 1 builtins.bin
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700695 5 builtins.bytearray.hex
696 5 builtins.bytes.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600697 3 builtins.float.as_integer_ratio
698 2 builtins.float.fromhex
699 2 builtins.float.hex
700 1 builtins.hex
701 1 builtins.int
Lisa Roach5ac70432018-09-13 23:56:23 -0700702 3 builtins.int.as_integer_ratio
Niklas Fiekas8bd216d2020-05-29 18:28:02 +0200703 2 builtins.int.bit_count
Zachary Warea4b7a752013-11-24 01:19:09 -0600704 2 builtins.int.bit_length
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700705 5 builtins.memoryview.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600706 1 builtins.oct
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -0700707 1 builtins.zip
Zachary Warea4b7a752013-11-24 01:19:09 -0600708
709Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
710'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
711and 'int' is a type.
Tim Peters8485b562004-08-04 18:46:34 +0000712"""
713
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500714
715class TestDocTestFinder(unittest.TestCase):
716
Miss Islington (bot)10d6f6b2021-05-05 11:01:21 -0700717 def test_issue35753(self):
718 # This import of `call` should trigger issue35753 when
719 # `support.run_doctest` is called due to unwrap failing,
720 # however with a patched doctest this should succeed.
721 from unittest.mock import call
722 dummy_module = types.ModuleType("dummy")
723 dummy_module.__dict__['inject_call'] = call
724 try:
725 support.run_doctest(dummy_module, verbosity=True)
726 except ValueError as e:
727 raise support.TestFailed("Doctest unwrap failed") from e
728
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500729 def test_empty_namespace_package(self):
730 pkg_name = 'doctest_empty_pkg'
Nick Coghland5d9e022018-03-25 23:03:10 +1000731 with tempfile.TemporaryDirectory() as parent_dir:
732 pkg_dir = os.path.join(parent_dir, pkg_name)
733 os.mkdir(pkg_dir)
734 sys.path.append(parent_dir)
735 try:
736 mod = importlib.import_module(pkg_name)
737 finally:
Hai Shi46605972020-08-04 00:49:18 +0800738 import_helper.forget(pkg_name)
Nick Coghland5d9e022018-03-25 23:03:10 +1000739 sys.path.pop()
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500740
Xtreak8289e272019-12-13 23:36:53 +0530741 include_empty_finder = doctest.DocTestFinder(exclude_empty=False)
742 exclude_empty_finder = doctest.DocTestFinder(exclude_empty=True)
743
744 self.assertEqual(len(include_empty_finder.find(mod)), 1)
745 self.assertEqual(len(exclude_empty_finder.find(mod)), 0)
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500746
Edward Loper00f8da72004-08-26 18:05:07 +0000747def test_DocTestParser(): r"""
748Unit tests for the `DocTestParser` class.
749
750DocTestParser is used to parse docstrings containing doctest examples.
751
752The `parse` method divides a docstring into examples and intervening
753text:
754
755 >>> s = '''
756 ... >>> x, y = 2, 3 # no output expected
757 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000758 ... ... print(x)
759 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000760 ... 2
761 ... 3
762 ...
763 ... Some text.
764 ... >>> x+y
765 ... 5
766 ... '''
767 >>> parser = doctest.DocTestParser()
768 >>> for piece in parser.parse(s):
769 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000770 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000771 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000772 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000773 Text: '\n'
774 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
775 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000776 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000777 Text: '\nSome text.\n'
778 Example: ('x+y\n', '5\n', 9)
779 Text: ''
780
781The `get_examples` method returns just the examples:
782
783 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000784 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000785 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000786 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000787 ('x+y\n', '5\n', 9)
788
789The `get_doctest` method creates a Test from the examples, along with the
790given arguments:
791
792 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
793 >>> (test.name, test.filename, test.lineno)
794 ('name', 'filename', 5)
795 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000796 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000797 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000798 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000799 ('x+y\n', '5\n', 9)
800"""
801
Tim Peters8485b562004-08-04 18:46:34 +0000802class test_DocTestRunner:
803 def basics(): r"""
804Unit tests for the `DocTestRunner` class.
805
806DocTestRunner is used to run DocTest test cases, and to accumulate
807statistics. Here's a simple DocTest case we can use:
808
809 >>> def f(x):
810 ... '''
811 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000812 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000813 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000814 ... >>> x//2
815 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000816 ... '''
817 >>> test = doctest.DocTestFinder().find(f)[0]
818
819The main DocTestRunner interface is the `run` method, which runs a
820given DocTest case in a given namespace (globs). It returns a tuple
821`(f,t)`, where `f` is the number of failed tests and `t` is the number
822of tried tests.
823
824 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000825 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000826
827If any example produces incorrect output, then the test runner reports
828the failure and proceeds to the next example:
829
830 >>> def f(x):
831 ... '''
832 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000833 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000834 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000835 ... >>> x//2
836 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000837 ... '''
838 >>> test = doctest.DocTestFinder().find(f)[0]
839 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000840 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000841 Trying:
842 x = 12
843 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000844 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000845 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000846 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000847 Expecting:
848 14
Tim Peters8485b562004-08-04 18:46:34 +0000849 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000850 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000851 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000852 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000853 Expected:
854 14
855 Got:
856 12
Edward Loperaacf0832004-08-26 01:19:50 +0000857 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000858 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000859 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000860 6
Tim Peters8485b562004-08-04 18:46:34 +0000861 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000862 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000863"""
864 def verbose_flag(): r"""
865The `verbose` flag makes the test runner generate more detailed
866output:
867
868 >>> def f(x):
869 ... '''
870 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000871 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000872 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000873 ... >>> x//2
874 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000875 ... '''
876 >>> test = doctest.DocTestFinder().find(f)[0]
877
878 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000879 Trying:
880 x = 12
881 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000882 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000883 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000884 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000885 Expecting:
886 12
Tim Peters8485b562004-08-04 18:46:34 +0000887 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000888 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000889 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000890 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000891 6
Tim Peters8485b562004-08-04 18:46:34 +0000892 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000893 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000894
895If the `verbose` flag is unspecified, then the output will be verbose
896iff `-v` appears in sys.argv:
897
898 >>> # Save the real sys.argv list.
899 >>> old_argv = sys.argv
900
901 >>> # If -v does not appear in sys.argv, then output isn't verbose.
902 >>> sys.argv = ['test']
903 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000904 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000905
906 >>> # If -v does appear in sys.argv, then output is verbose.
907 >>> sys.argv = ['test', '-v']
908 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000909 Trying:
910 x = 12
911 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000912 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000913 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000914 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000915 Expecting:
916 12
Tim Peters8485b562004-08-04 18:46:34 +0000917 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000918 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000919 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000920 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000921 6
Tim Peters8485b562004-08-04 18:46:34 +0000922 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000923 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000924
925 >>> # Restore sys.argv
926 >>> sys.argv = old_argv
927
928In the remaining examples, the test runner's verbosity will be
929explicitly set, to ensure that the test behavior is consistent.
930 """
931 def exceptions(): r"""
932Tests of `DocTestRunner`'s exception handling.
933
934An expected exception is specified with a traceback message. The
935lines between the first line and the type/value may be omitted or
936replaced with any other string:
937
938 >>> def f(x):
939 ... '''
940 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000941 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000942 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000943 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000944 ... '''
945 >>> test = doctest.DocTestFinder().find(f)[0]
946 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000947 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000948
Edward Loper19b19582004-08-25 23:07:03 +0000949An example may not generate output before it raises an exception; if
950it does, then the traceback message will not be recognized as
951signaling an expected exception, so the example will be reported as an
952unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000953
954 >>> def f(x):
955 ... '''
956 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000957 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000958 ... pre-exception output
959 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000960 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000961 ... '''
962 >>> test = doctest.DocTestFinder().find(f)[0]
963 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000964 ... # doctest: +ELLIPSIS
965 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000966 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000967 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000968 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000969 Exception raised:
970 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000971 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000972 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000973
974Exception messages may contain newlines:
975
976 >>> def f(x):
977 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000978 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000979 ... Traceback (most recent call last):
980 ... ValueError: multi
981 ... line
982 ... message
983 ... '''
984 >>> test = doctest.DocTestFinder().find(f)[0]
985 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000986 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000987
988If an exception is expected, but an exception with the wrong type or
989message is raised, then it is reported as a failure:
990
991 >>> def f(x):
992 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000993 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000994 ... Traceback (most recent call last):
995 ... ValueError: wrong message
996 ... '''
997 >>> test = doctest.DocTestFinder().find(f)[0]
998 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000999 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001000 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001001 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001002 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001003 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +00001004 Expected:
1005 Traceback (most recent call last):
1006 ValueError: wrong message
1007 Got:
1008 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +00001009 ...
Tim Peters8485b562004-08-04 18:46:34 +00001010 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001011 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001012
Tim Peters1fbf9c52004-09-04 17:21:02 +00001013However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
1014detail:
1015
1016 >>> def f(x):
1017 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001018 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001019 ... Traceback (most recent call last):
1020 ... ValueError: wrong message
1021 ... '''
1022 >>> test = doctest.DocTestFinder().find(f)[0]
1023 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001024 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001025
Nick Coghlan5e76e942010-06-12 13:42:46 +00001026IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
1027between Python versions. For example, in Python 2.x, the module path of
1028the exception is not in the output, but this will fail under Python 3:
1029
1030 >>> def f(x):
1031 ... r'''
1032 ... >>> from http.client import HTTPException
1033 ... >>> raise HTTPException('message')
1034 ... Traceback (most recent call last):
1035 ... HTTPException: message
1036 ... '''
1037 >>> test = doctest.DocTestFinder().find(f)[0]
1038 >>> doctest.DocTestRunner(verbose=False).run(test)
1039 ... # doctest: +ELLIPSIS
1040 **********************************************************************
1041 File ..., line 4, in f
1042 Failed example:
1043 raise HTTPException('message')
1044 Expected:
1045 Traceback (most recent call last):
1046 HTTPException: message
1047 Got:
1048 Traceback (most recent call last):
1049 ...
1050 http.client.HTTPException: message
1051 TestResults(failed=1, attempted=2)
1052
1053But in Python 3 the module path is included, and therefore a test must look
1054like the following test to succeed in Python 3. But that test will fail under
1055Python 2.
1056
1057 >>> def f(x):
1058 ... r'''
1059 ... >>> from http.client import HTTPException
1060 ... >>> raise HTTPException('message')
1061 ... Traceback (most recent call last):
1062 ... http.client.HTTPException: message
1063 ... '''
1064 >>> test = doctest.DocTestFinder().find(f)[0]
1065 >>> doctest.DocTestRunner(verbose=False).run(test)
1066 TestResults(failed=0, attempted=2)
1067
1068However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1069(or its unexpected absence) will be ignored:
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 ... HTTPException: message
1077 ... '''
1078 >>> test = doctest.DocTestFinder().find(f)[0]
1079 >>> doctest.DocTestRunner(verbose=False).run(test)
1080 TestResults(failed=0, attempted=2)
1081
1082The module path will be completely ignored, so two different module paths will
1083still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1084be used when exceptions have changed module.
1085
1086 >>> def f(x):
1087 ... r'''
1088 ... >>> from http.client import HTTPException
1089 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1090 ... Traceback (most recent call last):
1091 ... foo.bar.HTTPException: message
1092 ... '''
1093 >>> test = doctest.DocTestFinder().find(f)[0]
1094 >>> doctest.DocTestRunner(verbose=False).run(test)
1095 TestResults(failed=0, attempted=2)
1096
Tim Peters1fbf9c52004-09-04 17:21:02 +00001097But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1098
1099 >>> def f(x):
1100 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001101 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001102 ... Traceback (most recent call last):
1103 ... TypeError: wrong type
1104 ... '''
1105 >>> test = doctest.DocTestFinder().find(f)[0]
1106 >>> doctest.DocTestRunner(verbose=False).run(test)
1107 ... # doctest: +ELLIPSIS
1108 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001109 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001110 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001111 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001112 Expected:
1113 Traceback (most recent call last):
1114 TypeError: wrong type
1115 Got:
1116 Traceback (most recent call last):
1117 ...
1118 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001119 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001120
Tim Petersf9a07f22013-12-03 21:02:05 -06001121If the exception does not have a message, you can still use
1122IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1123
1124 >>> def f(x):
1125 ... r'''
1126 ... >>> from http.client import HTTPException
1127 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1128 ... Traceback (most recent call last):
1129 ... foo.bar.HTTPException
1130 ... '''
1131 >>> test = doctest.DocTestFinder().find(f)[0]
1132 >>> doctest.DocTestRunner(verbose=False).run(test)
1133 TestResults(failed=0, attempted=2)
1134
1135Note that a trailing colon doesn't matter either:
1136
1137 >>> def f(x):
1138 ... r'''
1139 ... >>> from http.client import HTTPException
1140 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1141 ... Traceback (most recent call last):
1142 ... foo.bar.HTTPException:
1143 ... '''
1144 >>> test = doctest.DocTestFinder().find(f)[0]
1145 >>> doctest.DocTestRunner(verbose=False).run(test)
1146 TestResults(failed=0, attempted=2)
1147
Tim Peters8485b562004-08-04 18:46:34 +00001148If an exception is raised but not expected, then it is reported as an
1149unexpected exception:
1150
Tim Peters8485b562004-08-04 18:46:34 +00001151 >>> def f(x):
1152 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001153 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001154 ... 0
1155 ... '''
1156 >>> test = doctest.DocTestFinder().find(f)[0]
1157 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001158 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001159 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001160 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001161 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001162 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001163 Exception raised:
1164 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001165 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001166 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001167 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001168"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001169 def displayhook(): r"""
1170Test that changing sys.displayhook doesn't matter for doctest.
1171
1172 >>> import sys
1173 >>> orig_displayhook = sys.displayhook
1174 >>> def my_displayhook(x):
1175 ... print('hi!')
1176 >>> sys.displayhook = my_displayhook
1177 >>> def f():
1178 ... '''
1179 ... >>> 3
1180 ... 3
1181 ... '''
1182 >>> test = doctest.DocTestFinder().find(f)[0]
1183 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1184 >>> post_displayhook = sys.displayhook
1185
1186 We need to restore sys.displayhook now, so that we'll be able to test
1187 results.
1188
1189 >>> sys.displayhook = orig_displayhook
1190
1191 Ok, now we can check that everything is ok.
1192
1193 >>> r
1194 TestResults(failed=0, attempted=1)
1195 >>> post_displayhook is my_displayhook
1196 True
1197"""
Tim Peters8485b562004-08-04 18:46:34 +00001198 def optionflags(): r"""
1199Tests of `DocTestRunner`'s option flag handling.
1200
1201Several option flags can be used to customize the behavior of the test
1202runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001203to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001204together).
1205
1206The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1207and 1/0:
1208
1209 >>> def f(x):
1210 ... '>>> True\n1\n'
1211
1212 >>> # Without the flag:
1213 >>> test = doctest.DocTestFinder().find(f)[0]
1214 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001215 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001216
1217 >>> # With the flag:
1218 >>> test = doctest.DocTestFinder().find(f)[0]
1219 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1220 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001221 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001222 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001223 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001224 Failed example:
1225 True
1226 Expected:
1227 1
1228 Got:
1229 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001230 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001231
1232The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1233and the '<BLANKLINE>' marker:
1234
1235 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001236 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001237
1238 >>> # Without the flag:
1239 >>> test = doctest.DocTestFinder().find(f)[0]
1240 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001241 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001242
1243 >>> # With the flag:
1244 >>> test = doctest.DocTestFinder().find(f)[0]
1245 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1246 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001247 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001248 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001249 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001250 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001251 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001252 Expected:
1253 a
1254 <BLANKLINE>
1255 b
1256 Got:
1257 a
1258 <BLANKLINE>
1259 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001260 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001261
1262The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1263treated as equal:
1264
1265 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001266 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001267
1268 >>> # Without the flag:
1269 >>> test = doctest.DocTestFinder().find(f)[0]
1270 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001271 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001272 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001273 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001274 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001275 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001276 Expected:
1277 1 2
1278 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001279 Got:
1280 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001281 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001282
1283 >>> # With the flag:
1284 >>> test = doctest.DocTestFinder().find(f)[0]
1285 >>> flags = doctest.NORMALIZE_WHITESPACE
1286 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001287 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001288
Tim Peters026f8dc2004-08-19 16:38:58 +00001289 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001290 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001291 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1292 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1293
Tim Peters8485b562004-08-04 18:46:34 +00001294The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1295output to match any substring in the actual output:
1296
1297 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001298 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001299
1300 >>> # Without the flag:
1301 >>> test = doctest.DocTestFinder().find(f)[0]
1302 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001303 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001304 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001305 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001306 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001307 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001308 Expected:
1309 [0, 1, 2, ..., 14]
1310 Got:
1311 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001312 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001313
1314 >>> # With the flag:
1315 >>> test = doctest.DocTestFinder().find(f)[0]
1316 >>> flags = doctest.ELLIPSIS
1317 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001318 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001319
Tim Peterse594bee2004-08-22 01:47:51 +00001320 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001321
Guido van Rossume0192e52007-02-09 23:39:59 +00001322 >>> if 1:
1323 ... for i in range(100):
1324 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1325 ... print('!')
1326 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001327
Tim Peters026f8dc2004-08-19 16:38:58 +00001328 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001329
Guido van Rossume0192e52007-02-09 23:39:59 +00001330 >>> if 1: #doctest: +ELLIPSIS
1331 ... for i in range(20):
1332 ... print(i, end=' ')
1333 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001334 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001335
Tim Peters026f8dc2004-08-19 16:38:58 +00001336 Examples from the docs:
1337
Guido van Rossum805365e2007-05-07 22:24:25 +00001338 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001339 [0, 1, ..., 18, 19]
1340
Guido van Rossum805365e2007-05-07 22:24:25 +00001341 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001342 ... # doctest: +NORMALIZE_WHITESPACE
1343 [0, 1, ..., 18, 19]
1344
Thomas Wouters477c8d52006-05-27 19:21:47 +00001345The SKIP flag causes an example to be skipped entirely. I.e., the
1346example is not run. It can be useful in contexts where doctest
1347examples serve as both documentation and test cases, and an example
1348should be included for documentation purposes, but should not be
1349checked (e.g., because its output is random, or depends on resources
1350which would be unavailable.) The SKIP flag can also be used for
1351'commenting out' broken examples.
1352
1353 >>> import unavailable_resource # doctest: +SKIP
1354 >>> unavailable_resource.do_something() # doctest: +SKIP
1355 >>> unavailable_resource.blow_up() # doctest: +SKIP
1356 Traceback (most recent call last):
1357 ...
1358 UncheckedBlowUpError: Nobody checks me.
1359
1360 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001361 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001362 0.721216923889
1363
Edward Loper71f55af2004-08-26 01:41:51 +00001364The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001365and actual outputs to be displayed using a unified diff:
1366
1367 >>> def f(x):
1368 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001369 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001370 ... a
1371 ... B
1372 ... c
1373 ... d
1374 ... f
1375 ... g
1376 ... h
1377 ... '''
1378
1379 >>> # Without the flag:
1380 >>> test = doctest.DocTestFinder().find(f)[0]
1381 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001382 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001383 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001384 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001385 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001386 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001387 Expected:
1388 a
1389 B
1390 c
1391 d
1392 f
1393 g
1394 h
1395 Got:
1396 a
1397 b
1398 c
1399 d
1400 e
1401 f
1402 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001403 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001404
1405 >>> # With the flag:
1406 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001407 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001408 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001409 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001410 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001411 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001412 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001413 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001414 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001415 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001416 a
1417 -B
1418 +b
1419 c
1420 d
1421 +e
1422 f
1423 g
1424 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001425 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001426
Edward Loper71f55af2004-08-26 01:41:51 +00001427The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001428and actual outputs to be displayed using a context diff:
1429
Edward Loper71f55af2004-08-26 01:41:51 +00001430 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001431 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001432 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001433 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001434 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001435 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001436 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001437 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001438 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001439 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001440 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001441 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001442 a
1443 ! B
1444 c
1445 d
1446 f
1447 g
1448 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001449 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001450 a
1451 ! b
1452 c
1453 d
1454 + e
1455 f
1456 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001457 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001458
1459
Edward Loper71f55af2004-08-26 01:41:51 +00001460The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001461used by the popular ndiff.py utility. This does intraline difference
1462marking, as well as interline differences.
1463
1464 >>> def f(x):
1465 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001466 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001467 ... a b c d e f g h i j k 1 m
1468 ... '''
1469 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001470 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001471 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001472 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001473 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001474 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001475 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001476 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001477 Differences (ndiff with -expected +actual):
1478 - a b c d e f g h i j k 1 m
1479 ? ^
1480 + a b c d e f g h i j k l m
1481 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001482 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001483
Ezio Melotti13925002011-03-16 11:05:33 +02001484The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001485failing example:
1486
1487 >>> def f(x):
1488 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001489 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001490 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001491 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001492 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001493 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001494 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001495 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001496 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001497 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001498 ... 500
1499 ... '''
1500 >>> test = doctest.DocTestFinder().find(f)[0]
1501 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1502 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001503 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001504 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001505 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001506 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001507 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001508 Expected:
1509 200
1510 Got:
1511 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001512 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001513
Ezio Melotti13925002011-03-16 11:05:33 +02001514However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001515
1516 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001517 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001518 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001519 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001520 Expecting:
1521 1
1522 ok
1523 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001524 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001525 Expecting:
1526 200
1527 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001528 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001529 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001530 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001531 Expected:
1532 200
1533 Got:
1534 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001535 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001536
R David Murray5a9d7062012-11-21 15:09:21 -05001537The FAIL_FAST flag causes the runner to exit after the first failing example,
1538so subsequent examples are not even attempted:
1539
1540 >>> flags = doctest.FAIL_FAST
1541 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1542 ... # doctest: +ELLIPSIS
1543 **********************************************************************
1544 File ..., line 5, in f
1545 Failed example:
1546 print(2) # first failure
1547 Expected:
1548 200
1549 Got:
1550 2
1551 TestResults(failed=1, attempted=2)
1552
1553Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1554FAIL_FAST only:
1555
1556 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1557 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1558 ... # doctest: +ELLIPSIS
1559 **********************************************************************
1560 File ..., line 5, in f
1561 Failed example:
1562 print(2) # first failure
1563 Expected:
1564 200
1565 Got:
1566 2
1567 TestResults(failed=1, attempted=2)
1568
1569For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1570exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001571
1572 >>> def f(x):
1573 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001574 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001575 ... 1
1576 ... >>> raise ValueError(2) # first failure
1577 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001578 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001579 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001580 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001581 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001582 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001583 ... 500
1584 ... '''
1585 >>> test = doctest.DocTestFinder().find(f)[0]
1586 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1587 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1588 ... # doctest: +ELLIPSIS
1589 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001590 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001591 Failed example:
1592 raise ValueError(2) # first failure
1593 Exception raised:
1594 ...
1595 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001596 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001597 >>> flags = doctest.FAIL_FAST
1598 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1599 ... # doctest: +ELLIPSIS
1600 **********************************************************************
1601 File ..., line 5, in f
1602 Failed example:
1603 raise ValueError(2) # first failure
1604 Exception raised:
1605 ...
1606 ValueError: 2
1607 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001608
Thomas Wouters477c8d52006-05-27 19:21:47 +00001609New option flags can also be registered, via register_optionflag(). Here
1610we reach into doctest's internals a bit.
1611
1612 >>> unlikely = "UNLIKELY_OPTION_NAME"
1613 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1614 False
1615 >>> new_flag_value = doctest.register_optionflag(unlikely)
1616 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1617 True
1618
1619Before 2.4.4/2.5, registering a name more than once erroneously created
1620more than one flag value. Here we verify that's fixed:
1621
1622 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1623 >>> redundant_flag_value == new_flag_value
1624 True
1625
1626Clean up.
1627 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1628
Tim Petersc6cbab02004-08-22 19:43:28 +00001629 """
1630
Tim Peters8485b562004-08-04 18:46:34 +00001631 def option_directives(): r"""
1632Tests of `DocTestRunner`'s option directive mechanism.
1633
Edward Loper74bca7a2004-08-12 02:27:44 +00001634Option directives can be used to turn option flags on or off for a
1635single example. To turn an option on for an example, follow that
1636example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001637
1638 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001639 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001640 ... [0, 1, ..., 9]
1641 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001642 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001643 ... [0, 1, ..., 9]
1644 ... '''
1645 >>> test = doctest.DocTestFinder().find(f)[0]
1646 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001647 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001648 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001649 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001650 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001651 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001652 Expected:
1653 [0, 1, ..., 9]
1654 Got:
1655 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001656 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001657
1658To turn an option off for an example, follow that example with a
1659comment of the form ``# doctest: -OPTION``:
1660
1661 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001662 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001663 ... [0, 1, ..., 9]
1664 ...
1665 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001666 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001667 ... [0, 1, ..., 9]
1668 ... '''
1669 >>> test = doctest.DocTestFinder().find(f)[0]
1670 >>> doctest.DocTestRunner(verbose=False,
1671 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001672 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001673 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001674 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001675 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001676 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001677 Expected:
1678 [0, 1, ..., 9]
1679 Got:
1680 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001681 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001682
1683Option directives affect only the example that they appear with; they
1684do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001685
Edward Loper74bca7a2004-08-12 02:27:44 +00001686 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001687 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001688 ... [0, 1, ..., 9]
1689 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001690 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001691 ... [0, 1, ..., 9]
1692 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001693 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001694 ... [0, 1, ..., 9]
1695 ... '''
1696 >>> test = doctest.DocTestFinder().find(f)[0]
1697 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001698 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001699 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001700 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001701 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001702 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001703 Expected:
1704 [0, 1, ..., 9]
1705 Got:
1706 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001707 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001708 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001709 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001710 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001711 Expected:
1712 [0, 1, ..., 9]
1713 Got:
1714 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001715 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001716
Edward Loper74bca7a2004-08-12 02:27:44 +00001717Multiple options may be modified by a single option directive. They
1718may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001719
1720 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001721 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001722 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001723 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001724 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001725 ... [0, 1, ..., 9]
1726 ... '''
1727 >>> test = doctest.DocTestFinder().find(f)[0]
1728 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001729 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001730 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001731 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001732 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001733 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001734 Expected:
1735 [0, 1, ..., 9]
1736 Got:
1737 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001738 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001739
1740 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001741 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001742 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001743 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001744 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1745 ... [0, 1, ..., 9]
1746 ... '''
1747 >>> test = doctest.DocTestFinder().find(f)[0]
1748 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001749 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001750 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001751 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001752 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001753 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001754 Expected:
1755 [0, 1, ..., 9]
1756 Got:
1757 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001758 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001759
1760 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001761 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001762 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001763 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001764 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1765 ... [0, 1, ..., 9]
1766 ... '''
1767 >>> test = doctest.DocTestFinder().find(f)[0]
1768 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001769 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001770 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001771 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001772 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001773 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001774 Expected:
1775 [0, 1, ..., 9]
1776 Got:
1777 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001778 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001779
1780The option directive may be put on the line following the source, as
1781long as a continuation prompt is used:
1782
1783 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001784 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001785 ... ... # doctest: +ELLIPSIS
1786 ... [0, 1, ..., 9]
1787 ... '''
1788 >>> test = doctest.DocTestFinder().find(f)[0]
1789 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001790 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001791
Edward Loper74bca7a2004-08-12 02:27:44 +00001792For examples with multi-line source, the option directive may appear
1793at the end of any line:
1794
1795 >>> def f(x): r'''
1796 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001797 ... ... print(' ', x, end='', sep='')
1798 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001799 ...
1800 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001801 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1802 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001803 ... '''
1804 >>> test = doctest.DocTestFinder().find(f)[0]
1805 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001806 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001807
1808If more than one line of an example with multi-line source has an
1809option directive, then they are combined:
1810
1811 >>> def f(x): r'''
1812 ... Should fail (option directive not on the last line):
1813 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001814 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001815 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001816 ... '''
1817 >>> test = doctest.DocTestFinder().find(f)[0]
1818 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001819 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001820
1821It is an error to have a comment of the form ``# doctest:`` that is
1822*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1823``OPTION`` is an option that has been registered with
1824`register_option`:
1825
1826 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001827 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001828 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1829 Traceback (most recent call last):
1830 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1831
1832 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001833 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001834 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1835 Traceback (most recent call last):
1836 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1837
1838It is an error to use an option directive on a line that contains no
1839source:
1840
1841 >>> s = '>>> # doctest: +ELLIPSIS'
1842 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1843 Traceback (most recent call last):
1844 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 +00001845"""
1846
1847def test_testsource(): r"""
1848Unit tests for `testsource()`.
1849
1850The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001851test with that name in that module, and converts it to a script. The
1852example code is converted to regular Python code. The surrounding
1853words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001854
1855 >>> import test.test_doctest
1856 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001857 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001858 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001859 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001860 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001861 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001862 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001863 #
Edward Lopera5db6002004-08-12 02:41:30 +00001864 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001865 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001866
1867 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001868 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001869 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001870 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001871 ## 1
1872 ## 2
1873 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001874 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001875
1876 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001877 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001878 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001879 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001880 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001881 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001882 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001883 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001884 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001885"""
1886
1887def test_debug(): r"""
1888
1889Create a docstring that we want to debug:
1890
1891 >>> s = '''
1892 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001893 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001894 ... 12
1895 ... '''
1896
1897Create some fake stdin input, to feed to the debugger:
1898
Tim Peters8485b562004-08-04 18:46:34 +00001899 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001900 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001901
1902Run the debugger on the docstring, and then restore sys.stdin.
1903
Edward Loper2de91ba2004-08-27 02:07:46 +00001904 >>> try: doctest.debug_src(s)
1905 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001907 (Pdb) next
1908 12
Tim Peters8485b562004-08-04 18:46:34 +00001909 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001911 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001912 12
1913 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001914
1915"""
1916
Brett Cannon31f59292011-02-21 19:29:56 +00001917if not hasattr(sys, 'gettrace') or not sys.gettrace():
1918 def test_pdb_set_trace():
1919 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001920
Brett Cannon31f59292011-02-21 19:29:56 +00001921 You can use pdb.set_trace from a doctest. To do so, you must
1922 retrieve the set_trace function from the pdb module at the time
1923 you use it. The doctest module changes sys.stdout so that it can
1924 capture program output. It also temporarily replaces pdb.set_trace
1925 with a version that restores stdout. This is necessary for you to
1926 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001927
Brett Cannon31f59292011-02-21 19:29:56 +00001928 >>> doc = '''
1929 ... >>> x = 42
1930 ... >>> raise Exception('clé')
1931 ... Traceback (most recent call last):
1932 ... Exception: clé
1933 ... >>> import pdb; pdb.set_trace()
1934 ... '''
1935 >>> parser = doctest.DocTestParser()
1936 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1937 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001938
Brett Cannon31f59292011-02-21 19:29:56 +00001939 To demonstrate this, we'll create a fake standard input that
1940 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001941
Brett Cannon31f59292011-02-21 19:29:56 +00001942 >>> real_stdin = sys.stdin
1943 >>> sys.stdin = _FakeInput([
1944 ... 'print(x)', # print data defined by the example
1945 ... 'continue', # stop debugging
1946 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001947
Brett Cannon31f59292011-02-21 19:29:56 +00001948 >>> try: runner.run(test)
1949 ... finally: sys.stdin = real_stdin
1950 --Return--
1951 > <doctest foo-bar@baz[2]>(1)<module>()->None
1952 -> import pdb; pdb.set_trace()
1953 (Pdb) print(x)
1954 42
1955 (Pdb) continue
1956 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001957
Brett Cannon31f59292011-02-21 19:29:56 +00001958 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001959
Brett Cannon31f59292011-02-21 19:29:56 +00001960 >>> def calls_set_trace():
1961 ... y=2
1962 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001963
Brett Cannon31f59292011-02-21 19:29:56 +00001964 >>> doc = '''
1965 ... >>> x=1
1966 ... >>> calls_set_trace()
1967 ... '''
1968 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1969 >>> real_stdin = sys.stdin
1970 >>> sys.stdin = _FakeInput([
1971 ... 'print(y)', # print data defined in the function
1972 ... 'up', # out of function
1973 ... 'print(x)', # print data defined by the example
1974 ... 'continue', # stop debugging
1975 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001976
Brett Cannon31f59292011-02-21 19:29:56 +00001977 >>> try:
1978 ... runner.run(test)
1979 ... finally:
1980 ... sys.stdin = real_stdin
1981 --Return--
Serhiy Storchakae437a102016-04-24 21:41:02 +03001982 > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
Brett Cannon31f59292011-02-21 19:29:56 +00001983 -> import pdb; pdb.set_trace()
1984 (Pdb) print(y)
1985 2
1986 (Pdb) up
1987 > <doctest foo-bar@baz[1]>(1)<module>()
1988 -> calls_set_trace()
1989 (Pdb) print(x)
1990 1
1991 (Pdb) continue
1992 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001993
Brett Cannon31f59292011-02-21 19:29:56 +00001994 During interactive debugging, source code is shown, even for
1995 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001996
Brett Cannon31f59292011-02-21 19:29:56 +00001997 >>> doc = '''
1998 ... >>> def f(x):
1999 ... ... g(x*2)
2000 ... >>> def g(x):
2001 ... ... print(x+3)
2002 ... ... import pdb; pdb.set_trace()
2003 ... >>> f(3)
2004 ... '''
2005 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2006 >>> real_stdin = sys.stdin
2007 >>> sys.stdin = _FakeInput([
2008 ... 'list', # list source from example 2
2009 ... 'next', # return from g()
2010 ... 'list', # list source from example 1
2011 ... 'next', # return from f()
2012 ... 'list', # list source from example 3
2013 ... 'continue', # stop debugging
2014 ... ''])
2015 >>> try: runner.run(test)
2016 ... finally: sys.stdin = real_stdin
2017 ... # doctest: +NORMALIZE_WHITESPACE
2018 --Return--
2019 > <doctest foo-bar@baz[1]>(3)g()->None
2020 -> import pdb; pdb.set_trace()
2021 (Pdb) list
2022 1 def g(x):
2023 2 print(x+3)
2024 3 -> import pdb; pdb.set_trace()
2025 [EOF]
2026 (Pdb) next
2027 --Return--
2028 > <doctest foo-bar@baz[0]>(2)f()->None
2029 -> g(x*2)
2030 (Pdb) list
2031 1 def f(x):
2032 2 -> g(x*2)
2033 [EOF]
2034 (Pdb) next
2035 --Return--
2036 > <doctest foo-bar@baz[2]>(1)<module>()->None
2037 -> f(3)
2038 (Pdb) list
2039 1 -> f(3)
2040 [EOF]
2041 (Pdb) continue
2042 **********************************************************************
2043 File "foo-bar@baz.py", line 7, in foo-bar@baz
2044 Failed example:
2045 f(3)
2046 Expected nothing
2047 Got:
2048 9
2049 TestResults(failed=1, attempted=3)
2050 """
Jim Fulton356fd192004-08-09 11:34:47 +00002051
Brett Cannon31f59292011-02-21 19:29:56 +00002052 def test_pdb_set_trace_nested():
2053 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00002054
Brett Cannon31f59292011-02-21 19:29:56 +00002055 >>> class C(object):
2056 ... def calls_set_trace(self):
2057 ... y = 1
2058 ... import pdb; pdb.set_trace()
2059 ... self.f1()
2060 ... y = 2
2061 ... def f1(self):
2062 ... x = 1
2063 ... self.f2()
2064 ... x = 2
2065 ... def f2(self):
2066 ... z = 1
2067 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002068
Brett Cannon31f59292011-02-21 19:29:56 +00002069 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002070
Brett Cannon31f59292011-02-21 19:29:56 +00002071 >>> doc = '''
2072 ... >>> a = 1
2073 ... >>> calls_set_trace()
2074 ... '''
2075 >>> parser = doctest.DocTestParser()
2076 >>> runner = doctest.DocTestRunner(verbose=False)
2077 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2078 >>> real_stdin = sys.stdin
2079 >>> sys.stdin = _FakeInput([
2080 ... 'print(y)', # print data defined in the function
2081 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2082 ... 'up', 'print(x)',
2083 ... 'up', 'print(y)',
2084 ... 'up', 'print(foo)',
2085 ... 'continue', # stop debugging
2086 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002087
Brett Cannon31f59292011-02-21 19:29:56 +00002088 >>> try:
2089 ... runner.run(test)
2090 ... finally:
2091 ... sys.stdin = real_stdin
2092 ... # doctest: +REPORT_NDIFF
2093 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2094 -> self.f1()
2095 (Pdb) print(y)
2096 1
2097 (Pdb) step
2098 --Call--
2099 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2100 -> def f1(self):
2101 (Pdb) step
2102 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2103 -> x = 1
2104 (Pdb) step
2105 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2106 -> self.f2()
2107 (Pdb) step
2108 --Call--
2109 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2110 -> def f2(self):
2111 (Pdb) step
2112 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2113 -> z = 1
2114 (Pdb) step
2115 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2116 -> z = 2
2117 (Pdb) print(z)
2118 1
2119 (Pdb) up
2120 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2121 -> self.f2()
2122 (Pdb) print(x)
2123 1
2124 (Pdb) up
2125 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2126 -> self.f1()
2127 (Pdb) print(y)
2128 1
2129 (Pdb) up
2130 > <doctest foo-bar@baz[1]>(1)<module>()
2131 -> calls_set_trace()
2132 (Pdb) print(foo)
2133 *** NameError: name 'foo' is not defined
2134 (Pdb) continue
2135 TestResults(failed=0, attempted=2)
2136 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002137
Tim Peters19397e52004-08-06 22:02:59 +00002138def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002139 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002140
2141 We create a Suite by providing a module. A module can be provided
2142 by passing a module object:
2143
2144 >>> import unittest
2145 >>> import test.sample_doctest
2146 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2147 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002148 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002149
2150 We can also supply the module by name:
2151
2152 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2153 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002154 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002155
R David Murray5abd76a2012-09-10 10:15:58 -04002156 The module need not contain any doctest examples:
2157
2158 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2159 >>> suite.run(unittest.TestResult())
2160 <unittest.result.TestResult run=0 errors=0 failures=0>
2161
R David Murray1976d9b2014-04-14 20:28:36 -04002162 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002163
R David Murray1976d9b2014-04-14 20:28:36 -04002164 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002165 >>> suite.run(unittest.TestResult())
2166 <unittest.result.TestResult run=0 errors=0 failures=0>
2167
Tim Peters19397e52004-08-06 22:02:59 +00002168 We can use the current module:
2169
2170 >>> suite = test.sample_doctest.test_suite()
2171 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002172 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002173
R David Murray1976d9b2014-04-14 20:28:36 -04002174 We can also provide a DocTestFinder:
2175
2176 >>> finder = doctest.DocTestFinder()
2177 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2178 ... test_finder=finder)
2179 >>> suite.run(unittest.TestResult())
2180 <unittest.result.TestResult run=9 errors=0 failures=4>
2181
2182 The DocTestFinder need not return any tests:
2183
2184 >>> finder = doctest.DocTestFinder()
2185 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2186 ... test_finder=finder)
2187 >>> suite.run(unittest.TestResult())
2188 <unittest.result.TestResult run=0 errors=0 failures=0>
2189
Tim Peters19397e52004-08-06 22:02:59 +00002190 We can supply global variables. If we pass globs, they will be
2191 used instead of the module globals. Here we'll pass an empty
2192 globals, triggering an extra error:
2193
2194 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2195 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002196 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002197
2198 Alternatively, we can provide extra globals. Here we'll make an
2199 error go away by providing an extra global variable:
2200
2201 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2202 ... extraglobs={'y': 1})
2203 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002204 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002205
2206 You can pass option flags. Here we'll cause an extra error
2207 by disabling the blank-line feature:
2208
2209 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002210 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002211 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002212 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002213
Tim Peters1e277ee2004-08-07 05:37:52 +00002214 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002215
Jim Fultonf54bad42004-08-28 14:57:56 +00002216 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002217 ... import test.test_doctest
2218 ... test.test_doctest.sillySetup = True
2219
Jim Fultonf54bad42004-08-28 14:57:56 +00002220 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002221 ... import test.test_doctest
2222 ... del test.test_doctest.sillySetup
2223
2224 Here, we installed a silly variable that the test expects:
2225
2226 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2227 ... setUp=setUp, tearDown=tearDown)
2228 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002229 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002230
2231 But the tearDown restores sanity:
2232
2233 >>> import test.test_doctest
2234 >>> test.test_doctest.sillySetup
2235 Traceback (most recent call last):
2236 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002237 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002238
Berker Peksag4882cac2015-04-14 09:30:01 +03002239 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002240 we'll use the setUp function to supply the missing variable y:
2241
2242 >>> def setUp(test):
2243 ... test.globs['y'] = 1
2244
2245 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2246 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002247 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002248
2249 Here, we didn't need to use a tearDown function because we
2250 modified the test globals, which are a copy of the
2251 sample_doctest module dictionary. The test globals are
2252 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002253 """
2254
2255def test_DocFileSuite():
2256 """We can test tests found in text files using a DocFileSuite.
2257
2258 We create a suite by providing the names of one or more text
2259 files that include examples:
2260
2261 >>> import unittest
2262 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002263 ... 'test_doctest2.txt',
2264 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002265 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002266 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002267
2268 The test files are looked for in the directory containing the
2269 calling module. A package keyword argument can be provided to
2270 specify a different relative location.
2271
2272 >>> import unittest
2273 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2274 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002275 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002276 ... package='test')
2277 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002278 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002279
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002280 Support for using a package's __loader__.get_data() is also
2281 provided.
2282
2283 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002284 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002285 >>> if not hasattr(test, '__loader__'):
2286 ... test.__loader__ = pkgutil.get_loader(test)
2287 ... added_loader = True
2288 >>> try:
2289 ... suite = doctest.DocFileSuite('test_doctest.txt',
2290 ... 'test_doctest2.txt',
2291 ... 'test_doctest4.txt',
2292 ... package='test')
2293 ... suite.run(unittest.TestResult())
2294 ... finally:
2295 ... if added_loader:
2296 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002297 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002298
Edward Loper0273f5b2004-09-18 20:27:04 +00002299 '/' should be used as a path separator. It will be converted
2300 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002301
2302 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2303 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002304 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002305
Edward Loper0273f5b2004-09-18 20:27:04 +00002306 If DocFileSuite is used from an interactive session, then files
2307 are resolved relative to the directory of sys.argv[0]:
2308
Christian Heimes45f9af32007-11-27 21:50:00 +00002309 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002310 >>> save_argv = sys.argv
2311 >>> sys.argv = [test.test_doctest.__file__]
2312 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002313 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002314 >>> sys.argv = save_argv
2315
Edward Loper052d0cd2004-09-19 17:19:33 +00002316 By setting `module_relative=False`, os-specific paths may be
2317 used (including absolute paths and paths relative to the
2318 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002319
2320 >>> # Get the absolute path of the test package.
2321 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2322 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2323
2324 >>> # Use it to find the absolute path of test_doctest.txt.
2325 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2326
Edward Loper052d0cd2004-09-19 17:19:33 +00002327 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002328 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002329 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002330
Edward Loper052d0cd2004-09-19 17:19:33 +00002331 It is an error to specify `package` when `module_relative=False`:
2332
2333 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2334 ... package='test')
2335 Traceback (most recent call last):
2336 ValueError: Package may only be specified for module-relative paths.
2337
Tim Peters19397e52004-08-06 22:02:59 +00002338 You can specify initial global variables:
2339
2340 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2341 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002342 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002343 ... globs={'favorite_color': 'blue'})
2344 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002345 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002346
2347 In this case, we supplied a missing favorite color. You can
2348 provide doctest options:
2349
2350 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2351 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002352 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002353 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2354 ... globs={'favorite_color': 'blue'})
2355 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002356 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002357
2358 And, you can provide setUp and tearDown functions:
2359
Jim Fultonf54bad42004-08-28 14:57:56 +00002360 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002361 ... import test.test_doctest
2362 ... test.test_doctest.sillySetup = True
2363
Jim Fultonf54bad42004-08-28 14:57:56 +00002364 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002365 ... import test.test_doctest
2366 ... del test.test_doctest.sillySetup
2367
2368 Here, we installed a silly variable that the test expects:
2369
2370 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2371 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002372 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002373 ... setUp=setUp, tearDown=tearDown)
2374 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002375 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002376
2377 But the tearDown restores sanity:
2378
2379 >>> import test.test_doctest
2380 >>> test.test_doctest.sillySetup
2381 Traceback (most recent call last):
2382 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002383 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002384
Berker Peksag4882cac2015-04-14 09:30:01 +03002385 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002386 Here, we'll use a setUp function to set the favorite color in
2387 test_doctest.txt:
2388
2389 >>> def setUp(test):
2390 ... test.globs['favorite_color'] = 'blue'
2391
2392 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2393 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002394 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002395
2396 Here, we didn't need to use a tearDown function because we
2397 modified the test globals. The test globals are
2398 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002399
Fred Drake7c404a42004-12-21 23:46:34 +00002400 Tests in a file run using `DocFileSuite` can also access the
2401 `__file__` global, which is set to the name of the file
2402 containing the tests:
2403
Benjamin Petersonab078e92016-07-13 21:13:29 -07002404 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
Fred Drake7c404a42004-12-21 23:46:34 +00002405 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002406 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002407
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002408 If the tests contain non-ASCII characters, we have to specify which
2409 encoding the file is encoded with. We do so by using the `encoding`
2410 parameter:
2411
2412 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2413 ... 'test_doctest2.txt',
2414 ... 'test_doctest4.txt',
2415 ... encoding='utf-8')
2416 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002417 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002418
Jim Fultonf54bad42004-08-28 14:57:56 +00002419 """
Tim Peters19397e52004-08-06 22:02:59 +00002420
Jim Fulton07a349c2004-08-22 14:10:00 +00002421def test_trailing_space_in_test():
2422 """
Tim Petersa7def722004-08-23 22:13:22 +00002423 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002424
Jim Fulton07a349c2004-08-22 14:10:00 +00002425 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002426 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002427 foo \n
2428 """
Tim Peters19397e52004-08-06 22:02:59 +00002429
Yury Selivanovb532df62014-12-08 15:00:05 -05002430class Wrapper:
2431 def __init__(self, func):
2432 self.func = func
2433 functools.update_wrapper(self, func)
2434
2435 def __call__(self, *args, **kwargs):
2436 self.func(*args, **kwargs)
2437
2438@Wrapper
2439def test_look_in_unwrapped():
2440 """
2441 Docstrings in wrapped functions must be detected as well.
2442
2443 >>> 'one other test'
2444 'one other test'
2445 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002446
2447def test_unittest_reportflags():
2448 """Default unittest reporting flags can be set to control reporting
2449
2450 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2451 only the first failure of each test. First, we'll look at the
2452 output without the flag. The file test_doctest.txt file has two
2453 tests. They both fail if blank lines are disabled:
2454
2455 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2456 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2457 >>> import unittest
2458 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002459 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002460 Traceback ...
2461 Failed example:
2462 favorite_color
2463 ...
2464 Failed example:
2465 if 1:
2466 ...
2467
2468 Note that we see both failures displayed.
2469
2470 >>> old = doctest.set_unittest_reportflags(
2471 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2472
2473 Now, when we run the test:
2474
2475 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002476 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002477 Traceback ...
2478 Failed example:
2479 favorite_color
2480 Exception raised:
2481 ...
2482 NameError: name 'favorite_color' is not defined
2483 <BLANKLINE>
2484 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002485
Jim Fultonf54bad42004-08-28 14:57:56 +00002486 We get only the first failure.
2487
2488 If we give any reporting options when we set up the tests,
2489 however:
2490
2491 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2492 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2493
2494 Then the default eporting options are ignored:
2495
2496 >>> result = suite.run(unittest.TestResult())
Pablo Galindoc5dc60e2019-01-10 14:29:40 +00002497
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302498 *NOTE*: These doctest are intentionally not placed in raw string to depict
2499 the trailing whitespace using `\x20` in the diff below.
2500
Guido van Rossum7131f842007-02-09 20:13:25 +00002501 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002502 Traceback ...
2503 Failed example:
2504 favorite_color
2505 ...
2506 Failed example:
2507 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002508 print('a')
2509 print()
2510 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002511 Differences (ndiff with -expected +actual):
2512 a
2513 - <BLANKLINE>
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302514 +\x20
Jim Fultonf54bad42004-08-28 14:57:56 +00002515 b
2516 <BLANKLINE>
2517 <BLANKLINE>
2518
2519
2520 Test runners can restore the formatting flags after they run:
2521
2522 >>> ignored = doctest.set_unittest_reportflags(old)
2523
2524 """
2525
Edward Loper052d0cd2004-09-19 17:19:33 +00002526def test_testfile(): r"""
2527Tests for the `testfile()` function. This function runs all the
Min ho Kimc4cacc82019-07-31 08:16:13 +10002528doctest examples in a given file. In its simple invocation, it is
Edward Loper052d0cd2004-09-19 17:19:33 +00002529called with the name of a file, which is taken to be relative to the
2530calling module. The return value is (#failures, #tests).
2531
Florent Xicluna59250852010-02-27 14:21:57 +00002532We don't want `-v` in sys.argv for these tests.
2533
2534 >>> save_argv = sys.argv
2535 >>> if '-v' in sys.argv:
2536 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2537
2538
Edward Loper052d0cd2004-09-19 17:19:33 +00002539 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2540 **********************************************************************
2541 File "...", line 6, in test_doctest.txt
2542 Failed example:
2543 favorite_color
2544 Exception raised:
2545 ...
2546 NameError: name 'favorite_color' is not defined
2547 **********************************************************************
2548 1 items had failures:
2549 1 of 2 in test_doctest.txt
2550 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002551 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002552 >>> doctest.master = None # Reset master.
2553
2554(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002555`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002556same name.)
2557
2558Globals may be specified with the `globs` and `extraglobs` parameters:
2559
2560 >>> globs = {'favorite_color': 'blue'}
2561 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002562 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002563 >>> doctest.master = None # Reset master.
2564
2565 >>> extraglobs = {'favorite_color': 'red'}
2566 >>> doctest.testfile('test_doctest.txt', globs=globs,
2567 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2568 **********************************************************************
2569 File "...", line 6, in test_doctest.txt
2570 Failed example:
2571 favorite_color
2572 Expected:
2573 'blue'
2574 Got:
2575 'red'
2576 **********************************************************************
2577 1 items had failures:
2578 1 of 2 in test_doctest.txt
2579 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002580 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002581 >>> doctest.master = None # Reset master.
2582
2583The file may be made relative to a given module or package, using the
2584optional `module_relative` parameter:
2585
2586 >>> doctest.testfile('test_doctest.txt', globs=globs,
2587 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002588 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002589 >>> doctest.master = None # Reset master.
2590
Ezio Melotti13925002011-03-16 11:05:33 +02002591Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002592
2593 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2594 Trying:
2595 favorite_color
2596 Expecting:
2597 'blue'
2598 ok
2599 Trying:
2600 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002601 print('a')
2602 print()
2603 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002604 Expecting:
2605 a
2606 <BLANKLINE>
2607 b
2608 ok
2609 1 items passed all tests:
2610 2 tests in test_doctest.txt
2611 2 tests in 1 items.
2612 2 passed and 0 failed.
2613 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002614 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002615 >>> doctest.master = None # Reset master.
2616
2617The name of the test may be specified with the optional `name`
2618parameter:
2619
2620 >>> doctest.testfile('test_doctest.txt', name='newname')
2621 ... # doctest: +ELLIPSIS
2622 **********************************************************************
2623 File "...", line 6, in newname
2624 ...
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
Ezio Melotti13925002011-03-16 11:05:33 +02002628The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002629parameter:
2630
2631 >>> doctest.testfile('test_doctest.txt', report=False)
2632 ... # doctest: +ELLIPSIS
2633 **********************************************************************
2634 File "...", line 6, in test_doctest.txt
2635 Failed example:
2636 favorite_color
2637 Exception raised:
2638 ...
2639 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002640 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002641 >>> doctest.master = None # Reset master.
2642
2643The optional keyword argument `raise_on_error` can be used to raise an
2644exception on the first error (which may be useful for postmortem
2645debugging):
2646
2647 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2648 ... # doctest: +ELLIPSIS
2649 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002650 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002651 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002652
2653If the tests contain non-ASCII characters, the tests might fail, since
2654it's unknown which encoding is used. The encoding can be specified
2655using the optional keyword argument `encoding`:
2656
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002657 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002658 **********************************************************************
2659 File "...", line 7, in test_doctest4.txt
2660 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002661 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002662 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002663 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002664 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002665 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002666 **********************************************************************
2667 ...
2668 **********************************************************************
2669 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002670 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002671 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002672 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002673 >>> doctest.master = None # Reset master.
2674
2675 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002676 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002677 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002678
2679Test the verbose output:
2680
2681 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2682 Trying:
2683 'föö'
2684 Expecting:
2685 'f\xf6\xf6'
2686 ok
2687 Trying:
2688 'bÄ…r'
2689 Expecting:
2690 'b\u0105r'
2691 ok
2692 1 items passed all tests:
2693 2 tests in test_doctest4.txt
2694 2 tests in 1 items.
2695 2 passed and 0 failed.
2696 Test passed.
2697 TestResults(failed=0, attempted=2)
2698 >>> doctest.master = None # Reset master.
2699 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002700"""
2701
Peter Donise0b81012020-03-26 11:53:16 -04002702class TestImporter(importlib.abc.MetaPathFinder, importlib.abc.ResourceLoader):
2703
2704 def find_spec(self, fullname, path, target=None):
2705 return importlib.util.spec_from_file_location(fullname, path, loader=self)
2706
2707 def get_data(self, path):
2708 with open(path, mode='rb') as f:
2709 return f.read()
2710
2711class TestHook:
2712
2713 def __init__(self, pathdir):
2714 self.sys_path = sys.path[:]
2715 self.meta_path = sys.meta_path[:]
2716 self.path_hooks = sys.path_hooks[:]
2717 sys.path.append(pathdir)
2718 sys.path_importer_cache.clear()
2719 self.modules_before = sys.modules.copy()
2720 self.importer = TestImporter()
2721 sys.meta_path.append(self.importer)
2722
2723 def remove(self):
2724 sys.path[:] = self.sys_path
2725 sys.meta_path[:] = self.meta_path
2726 sys.path_hooks[:] = self.path_hooks
2727 sys.path_importer_cache.clear()
2728 sys.modules.clear()
2729 sys.modules.update(self.modules_before)
2730
2731
2732@contextlib.contextmanager
2733def test_hook(pathdir):
2734 hook = TestHook(pathdir)
2735 try:
2736 yield hook
2737 finally:
2738 hook.remove()
2739
2740
R David Murrayb48cb292014-10-02 22:42:42 -04002741def test_lineendings(): r"""
Peter Donise0b81012020-03-26 11:53:16 -04002742*nix systems use \n line endings, while Windows systems use \r\n, and
2743old Mac systems used \r, which Python still recognizes as a line ending. Python
R David Murrayb48cb292014-10-02 22:42:42 -04002744handles this using universal newline mode for reading files. Let's make
2745sure doctest does so (issue 8473) by creating temporary test files using each
Peter Donise0b81012020-03-26 11:53:16 -04002746of the three line disciplines. At least one will not match either the universal
2747newline \n or os.linesep for the platform the test is run on.
R David Murrayb48cb292014-10-02 22:42:42 -04002748
2749Windows line endings first:
2750
2751 >>> import tempfile, os
2752 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002753 >>> with open(fn, 'wb') as f:
2754 ... 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 -04002755 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002756 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002757 TestResults(failed=0, attempted=1)
2758 >>> os.remove(fn)
2759
2760And now *nix line endings:
2761
2762 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002763 >>> with open(fn, 'wb') as f:
2764 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002765 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002766 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002767 TestResults(failed=0, attempted=1)
2768 >>> os.remove(fn)
2769
Peter Donise0b81012020-03-26 11:53:16 -04002770And finally old Mac line endings:
2771
2772 >>> fn = tempfile.mktemp()
2773 >>> with open(fn, 'wb') as f:
2774 ... f.write(b'Test:\r\r >>> x = 1 + 1\r\rDone.\r')
2775 30
2776 >>> doctest.testfile(fn, module_relative=False, verbose=False)
2777 TestResults(failed=0, attempted=1)
2778 >>> os.remove(fn)
2779
2780Now we test with a package loader that has a get_data method, since that
2781bypasses the standard universal newline handling so doctest has to do the
2782newline conversion itself; let's make sure it does so correctly (issue 1812).
2783We'll write a file inside the package that has all three kinds of line endings
2784in it, and use a package hook to install a custom loader; on any platform,
2785at least one of the line endings will raise a ValueError for inconsistent
2786whitespace if doctest does not correctly do the newline conversion.
2787
2788 >>> dn = tempfile.mkdtemp()
2789 >>> pkg = os.path.join(dn, "doctest_testpkg")
2790 >>> os.mkdir(pkg)
Hai Shi46605972020-08-04 00:49:18 +08002791 >>> os_helper.create_empty_file(os.path.join(pkg, "__init__.py"))
Peter Donise0b81012020-03-26 11:53:16 -04002792 >>> fn = os.path.join(pkg, "doctest_testfile.txt")
2793 >>> with open(fn, 'wb') as f:
2794 ... f.write(
2795 ... b'Test:\r\n\r\n'
2796 ... b' >>> x = 1 + 1\r\n\r\n'
2797 ... b'Done.\r\n'
2798 ... b'Test:\n\n'
2799 ... b' >>> x = 1 + 1\n\n'
2800 ... b'Done.\n'
2801 ... b'Test:\r\r'
2802 ... b' >>> x = 1 + 1\r\r'
2803 ... b'Done.\r'
2804 ... )
2805 95
2806 >>> with test_hook(dn):
2807 ... doctest.testfile("doctest_testfile.txt", package="doctest_testpkg", verbose=False)
2808 TestResults(failed=0, attempted=3)
2809 >>> shutil.rmtree(dn)
2810
R David Murrayb48cb292014-10-02 22:42:42 -04002811"""
2812
R. David Murray58641de2009-06-12 15:33:19 +00002813def test_testmod(): r"""
2814Tests for the testmod function. More might be useful, but for now we're just
2815testing the case raised by Issue 6195, where trying to doctest a C module would
2816fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2817out of the binary module.
2818
2819 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002820 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002821 TestResults(failed=0, attempted=0)
2822"""
2823
Victor Stinner9d396392010-10-16 21:54:59 +00002824try:
2825 os.fsencode("foo-bär@baz.py")
2826except UnicodeEncodeError:
2827 # Skip the test: the filesystem encoding is unable to encode the filename
2828 pass
2829else:
2830 def test_unicode(): """
2831Check doctest with a non-ascii filename:
2832
2833 >>> doc = '''
2834 ... >>> raise Exception('clé')
2835 ... '''
2836 ...
2837 >>> parser = doctest.DocTestParser()
2838 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2839 >>> test
2840 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2841 >>> runner = doctest.DocTestRunner(verbose=False)
2842 >>> runner.run(test) # doctest: +ELLIPSIS
2843 **********************************************************************
2844 File "foo-bär@baz.py", line 2, in foo-bär@baz
2845 Failed example:
2846 raise Exception('clé')
2847 Exception raised:
2848 Traceback (most recent call last):
2849 File ...
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03002850 exec(compile(example.source, filename, "single",
Victor Stinner9d396392010-10-16 21:54:59 +00002851 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2852 raise Exception('clé')
2853 Exception: clé
2854 TestResults(failed=1, attempted=1)
2855 """
2856
R David Murray5707d502013-06-23 14:24:13 -04002857def test_CLI(): r"""
2858The doctest module can be used to run doctests against an arbitrary file.
2859These tests test this CLI functionality.
2860
2861We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002862to a temp dir to run the command against. Due to a current limitation in
2863script_helpers, though, we need a little utility function to turn the returned
2864output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002865
R David Murray4af68982013-06-25 08:11:22 -04002866 >>> def normalize(s):
2867 ... return '\n'.join(s.decode().splitlines())
2868
R David Murray4af68982013-06-25 08:11:22 -04002869With those preliminaries out of the way, we'll start with a file with two
2870simple tests and no errors. We'll run both the unadorned doctest command, and
2871the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002872
Hai Shi46605972020-08-04 00:49:18 +08002873 >>> from test.support import script_helper
2874 >>> from test.support.os_helper import temp_dir
Berker Peksagce643912015-05-06 06:33:17 +03002875 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002876 ... fn = os.path.join(tmpdir, 'myfile.doc')
Inada Naoki8bbfeb32021-04-02 12:53:46 +09002877 ... with open(fn, 'w', encoding='utf-8') as f:
R David Murray5707d502013-06-23 14:24:13 -04002878 ... _ = f.write('This is a very simple test file.\n')
2879 ... _ = f.write(' >>> 1 + 1\n')
2880 ... _ = f.write(' 2\n')
2881 ... _ = f.write(' >>> "a"\n')
2882 ... _ = f.write(" 'a'\n")
2883 ... _ = f.write('\n')
2884 ... _ = f.write('And that is it.\n')
2885 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002886 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002887 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002888 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002889
2890With no arguments and passing tests, we should get no output:
2891
2892 >>> rc1, out1, err1
2893 (0, b'', b'')
2894
2895With the verbose flag, we should see the test output, but no error output:
2896
2897 >>> rc2, err2
2898 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002899 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002900 Trying:
2901 1 + 1
2902 Expecting:
2903 2
2904 ok
2905 Trying:
2906 "a"
2907 Expecting:
2908 'a'
2909 ok
2910 1 items passed all tests:
2911 2 tests in myfile.doc
2912 2 tests in 1 items.
2913 2 passed and 0 failed.
2914 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002915
2916Now we'll write a couple files, one with three tests, the other a python module
2917with two tests, both of the files having "errors" in the tests that can be made
2918non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2919the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002920allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002921ability to process more than one file on the command line and, since the second
2922file ends in '.py', its handling of python module files (as opposed to straight
2923text files).
2924
Hai Shi46605972020-08-04 00:49:18 +08002925 >>> from test.support import script_helper
2926 >>> from test.support.os_helper import temp_dir
Berker Peksagce643912015-05-06 06:33:17 +03002927 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002928 ... fn = os.path.join(tmpdir, 'myfile.doc')
Inada Naoki8bbfeb32021-04-02 12:53:46 +09002929 ... with open(fn, 'w', encoding="utf-8") as f:
R David Murray5707d502013-06-23 14:24:13 -04002930 ... _ = f.write('This is another simple test file.\n')
2931 ... _ = f.write(' >>> 1 + 1\n')
2932 ... _ = f.write(' 2\n')
2933 ... _ = f.write(' >>> "abcdef"\n')
2934 ... _ = f.write(" 'a...f'\n")
2935 ... _ = f.write(' >>> "ajkml"\n')
2936 ... _ = f.write(" 'a...l'\n")
2937 ... _ = f.write('\n')
2938 ... _ = f.write('And that is it.\n')
2939 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
Inada Naoki8bbfeb32021-04-02 12:53:46 +09002940 ... with open(fn2, 'w', encoding='utf-8') as f:
R David Murray5707d502013-06-23 14:24:13 -04002941 ... _ = f.write('def test_func():\n')
2942 ... _ = f.write(' \"\"\"\n')
2943 ... _ = f.write(' This is simple python test function.\n')
2944 ... _ = f.write(' >>> 1 + 1\n')
2945 ... _ = f.write(' 2\n')
2946 ... _ = f.write(' >>> "abc def"\n')
2947 ... _ = f.write(" 'abc def'\n")
2948 ... _ = f.write("\n")
2949 ... _ = f.write(' \"\"\"\n')
R David Murray5707d502013-06-23 14:24:13 -04002950 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002951 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002952 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002953 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002954 ... rc3, out3, err3 = script_helper.assert_python_ok(
2955 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002956 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002957 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002958 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002959 ... rc5, out5, err5 = script_helper.assert_python_ok(
2960 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002961 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002962
2963Our first test run will show the errors from the first file (doctest stops if a
2964file has errors). Note that doctest test-run error output appears on stdout,
2965not stderr:
2966
2967 >>> rc1, err1
2968 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002969 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002970 **********************************************************************
2971 File "...myfile.doc", line 4, in myfile.doc
2972 Failed example:
2973 "abcdef"
2974 Expected:
2975 'a...f'
2976 Got:
2977 'abcdef'
2978 **********************************************************************
2979 File "...myfile.doc", line 6, in myfile.doc
2980 Failed example:
2981 "ajkml"
2982 Expected:
2983 'a...l'
2984 Got:
2985 'ajkml'
2986 **********************************************************************
2987 1 items had failures:
2988 2 of 3 in myfile.doc
2989 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002990
2991With -o ELLIPSIS specified, the second run, against just the first file, should
2992produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2993should the third, which ran against both files:
2994
2995 >>> rc2, out2, err2
2996 (0, b'', b'')
2997 >>> rc3, out3, err3
2998 (0, b'', b'')
2999
3000The fourth run uses FAIL_FAST, so we should see only one error:
3001
3002 >>> rc4, err4
3003 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04003004 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003005 **********************************************************************
3006 File "...myfile.doc", line 4, in myfile.doc
3007 Failed example:
3008 "abcdef"
3009 Expected:
3010 'a...f'
3011 Got:
3012 'abcdef'
3013 **********************************************************************
3014 1 items had failures:
3015 1 of 2 in myfile.doc
3016 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04003017
3018The fifth test uses verbose with the two options, so we should get verbose
3019success output for the tests in both files:
3020
3021 >>> rc5, err5
3022 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04003023 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04003024 Trying:
3025 1 + 1
3026 Expecting:
3027 2
3028 ok
3029 Trying:
3030 "abcdef"
3031 Expecting:
3032 'a...f'
3033 ok
3034 Trying:
3035 "ajkml"
3036 Expecting:
3037 'a...l'
3038 ok
3039 1 items passed all tests:
3040 3 tests in myfile.doc
3041 3 tests in 1 items.
3042 3 passed and 0 failed.
3043 Test passed.
3044 Trying:
3045 1 + 1
3046 Expecting:
3047 2
3048 ok
3049 Trying:
3050 "abc def"
3051 Expecting:
3052 'abc def'
3053 ok
3054 1 items had no tests:
3055 myfile2
3056 1 items passed all tests:
3057 2 tests in myfile2.test_func
3058 2 tests in 2 items.
3059 2 passed and 0 failed.
3060 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04003061
3062We should also check some typical error cases.
3063
3064Invalid file name:
3065
3066 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03003067 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04003068 >>> rc, out
3069 (1, b'')
pxinwr8d4f57d2020-12-05 04:19:32 +08003070 >>> # The exact error message changes depending on the platform.
R David Murray4af68982013-06-25 08:11:22 -04003071 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003072 Traceback (most recent call last):
3073 ...
pxinwr8d4f57d2020-12-05 04:19:32 +08003074 FileNotFoundError: [Errno ...] ...nosuchfile...
R David Murray5707d502013-06-23 14:24:13 -04003075
3076Invalid doctest option:
3077
3078 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03003079 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04003080 >>> rc, out
3081 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04003082 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04003083 usage...invalid...nosuchoption...
3084
3085"""
3086
Sanyam Khuranacbb16452019-01-09 19:08:38 +05303087def test_no_trailing_whitespace_stripping():
3088 r"""
3089 The fancy reports had a bug for a long time where any trailing whitespace on
3090 the reported diff lines was stripped, making it impossible to see the
3091 differences in line reported as different that differed only in the amount of
3092 trailing whitespace. The whitespace still isn't particularly visible unless
3093 you use NDIFF, but at least it is now there to be found.
3094
3095 *NOTE*: This snippet was intentionally put inside a raw string to get rid of
3096 leading whitespace error in executing the example below
3097
3098 >>> def f(x):
3099 ... r'''
3100 ... >>> print('\n'.join(['a ', 'b']))
3101 ... a
3102 ... b
3103 ... '''
3104 """
3105 """
3106 *NOTE*: These doctest are not placed in raw string to depict the trailing whitespace
3107 using `\x20`
3108
3109 >>> test = doctest.DocTestFinder().find(f)[0]
3110 >>> flags = doctest.REPORT_NDIFF
3111 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
3112 ... # doctest: +ELLIPSIS
3113 **********************************************************************
3114 File ..., line 3, in f
3115 Failed example:
3116 print('\n'.join(['a ', 'b']))
3117 Differences (ndiff with -expected +actual):
3118 - a
3119 + a
3120 b
3121 TestResults(failed=1, attempted=1)
3122
3123 *NOTE*: `\x20` is for checking the trailing whitespace on the +a line above.
3124 We cannot use actual spaces there, as a commit hook prevents from committing
3125 patches that contain trailing whitespace. More info on Issue 24746.
3126 """
3127
Tim Peters8485b562004-08-04 18:46:34 +00003128
Miss Islington (bot)65de8082021-10-20 09:52:22 -07003129def load_tests(loader, tests, pattern):
3130 tests.addTest(doctest.DocTestSuite(doctest))
3131 tests.addTest(doctest.DocTestSuite())
3132 return tests
Jason R. Coombsb9650a02018-03-05 18:29:08 -05003133
3134
Tim Peters8485b562004-08-04 18:46:34 +00003135def test_coverage(coverdir):
Hai Shi46605972020-08-04 00:49:18 +08003136 trace = import_helper.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01003137 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00003138 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00003139 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00003140 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003141 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00003142 r.write_results(show_missing=True, summary=True,
3143 coverdir=coverdir)
3144
Miss Islington (bot)65de8082021-10-20 09:52:22 -07003145
Tim Peters8485b562004-08-04 18:46:34 +00003146if __name__ == '__main__':
3147 if '-c' in sys.argv:
3148 test_coverage('/tmp/doctest.cover')
3149 else:
Miss Islington (bot)65de8082021-10-20 09:52:22 -07003150 unittest.main()