blob: f1013f25725964121225202cf666e57ed00b9e66 [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Yury Selivanovb532df62014-12-08 15:00:05 -05007import functools
Victor Stinner9d396392010-10-16 21:54:59 +00008import os
Brett Cannon31f59292011-02-21 19:29:56 +00009import sys
Jason R. Coombsb9650a02018-03-05 18:29:08 -050010import importlib
11import unittest
Nick Coghland5d9e022018-03-25 23:03:10 +100012import tempfile
Florent Xiclunadc6f2d02010-04-02 19:25:32 +000013
Nick Coghlanf088e5e2008-12-14 11:50:48 +000014# NOTE: There are some additional tests relating to interaction with
15# zipimport in the test_zipimport_support test module.
16
Tim Peters8485b562004-08-04 18:46:34 +000017######################################################################
18## Sample Objects (used by test cases)
19######################################################################
20
21def sample_func(v):
22 """
Tim Peters19397e52004-08-06 22:02:59 +000023 Blah blah
24
Guido van Rossum7131f842007-02-09 20:13:25 +000025 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000026 44
Tim Peters19397e52004-08-06 22:02:59 +000027
28 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000029 """
30 return v+v
31
32class SampleClass:
33 """
Guido van Rossum7131f842007-02-09 20:13:25 +000034 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000035 1
Edward Loper4ae900f2004-09-21 03:20:34 +000036
37 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
38 >>>
39 ...
40
41 Multiline example:
42 >>> sc = SampleClass(3)
43 >>> for i in range(10):
44 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000045 ... print(' ', sc.get(), sep='', end='')
46 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000047 """
48 def __init__(self, val):
49 """
Guido van Rossum7131f842007-02-09 20:13:25 +000050 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000051 12
52 """
53 self.val = val
54
55 def double(self):
56 """
Guido van Rossum7131f842007-02-09 20:13:25 +000057 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000058 24
59 """
60 return SampleClass(self.val + self.val)
61
62 def get(self):
63 """
Guido van Rossum7131f842007-02-09 20:13:25 +000064 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000065 -5
66 """
67 return self.val
68
69 def a_staticmethod(v):
70 """
Guido van Rossum7131f842007-02-09 20:13:25 +000071 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000072 11
73 """
74 return v+1
75 a_staticmethod = staticmethod(a_staticmethod)
76
77 def a_classmethod(cls, v):
78 """
Guido van Rossum7131f842007-02-09 20:13:25 +000079 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000080 12
Guido van Rossum7131f842007-02-09 20:13:25 +000081 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000082 12
83 """
84 return v+2
85 a_classmethod = classmethod(a_classmethod)
86
87 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000088 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000089 22
90 """)
91
92 class NestedClass:
93 """
94 >>> x = SampleClass.NestedClass(5)
95 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000096 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000097 25
98 """
99 def __init__(self, val=0):
100 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000101 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +0000102 0
103 """
104 self.val = val
105 def square(self):
106 return SampleClass.NestedClass(self.val*self.val)
107 def get(self):
108 return self.val
109
110class SampleNewStyleClass(object):
111 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000112 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000113 1
114 2
115 3
116 """
117 def __init__(self, val):
118 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000119 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000120 12
121 """
122 self.val = val
123
124 def double(self):
125 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000126 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000127 24
128 """
129 return SampleNewStyleClass(self.val + self.val)
130
131 def get(self):
132 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000133 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000134 -5
135 """
136 return self.val
137
138######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000139## Fake stdin (for testing interactive debugging)
140######################################################################
141
142class _FakeInput:
143 """
144 A fake input stream for pdb's interactive debugger. Whenever a
145 line is read, print it (to simulate the user typing it), and then
146 return it. The set of lines to return is specified in the
147 constructor; they should not have trailing newlines.
148 """
149 def __init__(self, lines):
150 self.lines = lines
151
152 def readline(self):
153 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000154 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000155 return line+'\n'
156
157######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000158## Test Cases
159######################################################################
160
161def test_Example(): r"""
162Unit tests for the `Example` class.
163
Edward Lopera6b68322004-08-26 00:05:43 +0000164Example is a simple container class that holds:
165 - `source`: A source string.
166 - `want`: An expected output string.
167 - `exc_msg`: An expected exception message string (or None if no
168 exception is expected).
169 - `lineno`: A line number (within the docstring).
170 - `indent`: The example's indentation in the input string.
171 - `options`: An option dictionary, mapping option flags to True or
172 False.
Tim Peters8485b562004-08-04 18:46:34 +0000173
Edward Lopera6b68322004-08-26 00:05:43 +0000174These attributes are set by the constructor. `source` and `want` are
175required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000176
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000177 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000178 >>> (example.source, example.want, example.exc_msg,
179 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000180 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000181
182The first three attributes (`source`, `want`, and `exc_msg`) may be
183specified positionally; the remaining arguments should be specified as
184keyword arguments:
185
186 >>> exc_msg = 'IndexError: pop from an empty list'
187 >>> example = doctest.Example('[].pop()', '', exc_msg,
188 ... lineno=5, indent=4,
189 ... options={doctest.ELLIPSIS: True})
190 >>> (example.source, example.want, example.exc_msg,
191 ... example.lineno, example.indent, example.options)
192 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
193
194The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000195
Tim Petersbb431472004-08-09 03:51:46 +0000196 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000197 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000198 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000199 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000200
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000201 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000202 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000203 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000204
Tim Petersbb431472004-08-09 03:51:46 +0000205 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000206 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000207 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000208 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000209
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000210 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000211 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000212 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000213
Edward Lopera6b68322004-08-26 00:05:43 +0000214 Empty source string (which should never appear in real examples)
215 >>> e = doctest.Example('', '')
216 >>> e.source, e.want
217 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000218
Edward Lopera6b68322004-08-26 00:05:43 +0000219The constructor normalizes the `want` string to end in a newline,
220unless it's the empty string:
221
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000222 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000223 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000224 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000225
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000226 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000227 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000228 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000229
Edward Lopera6b68322004-08-26 00:05:43 +0000230 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000231 >>> e.source, e.want
232 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000233
234The constructor normalizes the `exc_msg` string to end in a newline,
235unless it's `None`:
236
237 Message spans one line
238 >>> exc_msg = 'IndexError: pop from an empty list'
239 >>> e = doctest.Example('[].pop()', '', exc_msg)
240 >>> e.exc_msg
241 'IndexError: pop from an empty list\n'
242
243 >>> exc_msg = 'IndexError: pop from an empty list\n'
244 >>> e = doctest.Example('[].pop()', '', exc_msg)
245 >>> e.exc_msg
246 'IndexError: pop from an empty list\n'
247
248 Message spans multiple lines
249 >>> exc_msg = 'ValueError: 1\n 2'
250 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
251 >>> e.exc_msg
252 'ValueError: 1\n 2\n'
253
254 >>> exc_msg = 'ValueError: 1\n 2\n'
255 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
256 >>> e.exc_msg
257 'ValueError: 1\n 2\n'
258
259 Empty (but non-None) exception message (which should never appear
260 in real examples)
261 >>> exc_msg = ''
262 >>> e = doctest.Example('raise X()', '', exc_msg)
263 >>> e.exc_msg
264 '\n'
Antoine Pitrou165b1282011-12-18 20:20:17 +0100265
266Compare `Example`:
267 >>> example = doctest.Example('print 1', '1\n')
268 >>> same_example = doctest.Example('print 1', '1\n')
269 >>> other_example = doctest.Example('print 42', '42\n')
270 >>> example == same_example
271 True
272 >>> example != same_example
273 False
274 >>> hash(example) == hash(same_example)
275 True
276 >>> example == other_example
277 False
278 >>> example != other_example
279 True
Tim Peters8485b562004-08-04 18:46:34 +0000280"""
281
282def test_DocTest(): r"""
283Unit tests for the `DocTest` class.
284
285DocTest is a collection of examples, extracted from a docstring, along
286with information about where the docstring comes from (a name,
287filename, and line number). The docstring is parsed by the `DocTest`
288constructor:
289
290 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000291 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000292 ... 12
293 ...
294 ... Non-example text.
295 ...
R David Murray44b548d2016-09-08 13:59:53 -0400296 ... >>> print('another\\example')
Tim Peters8485b562004-08-04 18:46:34 +0000297 ... another
298 ... example
299 ... '''
300 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000301 >>> parser = doctest.DocTestParser()
302 >>> test = parser.get_doctest(docstring, globs, 'some_test',
303 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000304 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000305 <DocTest some_test from some_file:20 (2 examples)>
306 >>> len(test.examples)
307 2
308 >>> e1, e2 = test.examples
309 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000310 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000311 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000312 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000313
314Source information (name, filename, and line number) is available as
315attributes on the doctest object:
316
317 >>> (test.name, test.filename, test.lineno)
318 ('some_test', 'some_file', 20)
319
320The line number of an example within its containing file is found by
321adding the line number of the example and the line number of its
322containing test:
323
324 >>> test.lineno + e1.lineno
325 21
326 >>> test.lineno + e2.lineno
327 26
328
Martin Panter46f50722016-05-26 05:35:26 +0000329If the docstring contains inconsistent leading whitespace in the
Tim Peters8485b562004-08-04 18:46:34 +0000330expected output of an example, then `DocTest` will raise a ValueError:
331
332 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000333 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000334 ... bad
335 ... indentation
336 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000337 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000338 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000339 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000340
341If the docstring contains inconsistent leading whitespace on
342continuation lines, then `DocTest` will raise a ValueError:
343
344 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000345 ... >>> print(('bad indentation',
346 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000347 ... ('bad', 'indentation')
348 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000349 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000350 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000351 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000352
353If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
354will raise a ValueError:
355
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000356 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000357 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000358 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000359 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000360
361If there's no blank space after a PS2 prompt ('...'), then `DocTest`
362will raise a ValueError:
363
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000364 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000365 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000366 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000367 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000368
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100369Compare `DocTest`:
370
371 >>> docstring = '''
372 ... >>> print 12
373 ... 12
374 ... '''
375 >>> test = parser.get_doctest(docstring, globs, 'some_test',
376 ... 'some_test', 20)
377 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
378 ... 'some_test', 20)
379 >>> test == same_test
380 True
381 >>> test != same_test
382 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100383 >>> hash(test) == hash(same_test)
384 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100385 >>> docstring = '''
386 ... >>> print 42
387 ... 42
388 ... '''
389 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
390 ... 'other_file', 10)
391 >>> test == other_test
392 False
393 >>> test != other_test
394 True
395
396Compare `DocTestCase`:
397
398 >>> DocTestCase = doctest.DocTestCase
399 >>> test_case = DocTestCase(test)
400 >>> same_test_case = DocTestCase(same_test)
401 >>> other_test_case = DocTestCase(other_test)
402 >>> test_case == same_test_case
403 True
404 >>> test_case != same_test_case
405 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100406 >>> hash(test_case) == hash(same_test_case)
407 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100408 >>> test == other_test_case
409 False
410 >>> test != other_test_case
411 True
412
Tim Peters8485b562004-08-04 18:46:34 +0000413"""
414
Zachary Ware7119b452013-11-24 02:21:57 -0600415class test_DocTestFinder:
416 def basics(): r"""
Tim Peters8485b562004-08-04 18:46:34 +0000417Unit tests for the `DocTestFinder` class.
418
419DocTestFinder is used to extract DocTests from an object's docstring
420and the docstrings of its contained objects. It can be used with
421modules, functions, classes, methods, staticmethods, classmethods, and
422properties.
423
424Finding Tests in Functions
425~~~~~~~~~~~~~~~~~~~~~~~~~~
426For a function whose docstring contains examples, DocTestFinder.find()
427will return a single test (for that function's docstring):
428
Tim Peters8485b562004-08-04 18:46:34 +0000429 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000430
431We'll simulate a __file__ attr that ends in pyc:
432
433 >>> import test.test_doctest
434 >>> old = test.test_doctest.__file__
435 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
436
Tim Peters8485b562004-08-04 18:46:34 +0000437 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000438
Guido van Rossum7131f842007-02-09 20:13:25 +0000439 >>> print(tests) # doctest: +ELLIPSIS
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500440 [<DocTest sample_func from ...:21 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000441
Tim Peters4de7c5c2004-08-23 22:38:05 +0000442The exact name depends on how test_doctest was invoked, so allow for
443leading path components.
444
445 >>> tests[0].filename # doctest: +ELLIPSIS
446 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000447
448 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000449
Jim Fulton07a349c2004-08-22 14:10:00 +0000450
Tim Peters8485b562004-08-04 18:46:34 +0000451 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000452 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000453 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000454
Edward Loper32ddbf72004-09-13 05:47:24 +0000455By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000456
457 >>> def no_docstring(v):
458 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000459 >>> finder.find(no_docstring)
460 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000461
462However, the optional argument `exclude_empty` to the DocTestFinder
463constructor can be used to exclude tests for objects with empty
464docstrings:
465
466 >>> def no_docstring(v):
467 ... pass
468 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
469 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000470 []
471
472If the function has a docstring with no examples, then a test with no
473examples is returned. (This lets `DocTestRunner` collect statistics
474about which functions have no tests -- but is that useful? And should
475an empty test also be created when there's no docstring?)
476
477 >>> def no_examples(v):
478 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000479 >>> finder.find(no_examples) # doctest: +ELLIPSIS
480 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000481
482Finding Tests in Classes
483~~~~~~~~~~~~~~~~~~~~~~~~
484For a class, DocTestFinder will create a test for the class's
485docstring, and will recursively explore its contents, including
486methods, classmethods, staticmethods, properties, and nested classes.
487
488 >>> finder = doctest.DocTestFinder()
489 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000490 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000491 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000492 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000493 3 SampleClass.NestedClass
494 1 SampleClass.NestedClass.__init__
495 1 SampleClass.__init__
496 2 SampleClass.a_classmethod
497 1 SampleClass.a_property
498 1 SampleClass.a_staticmethod
499 1 SampleClass.double
500 1 SampleClass.get
501
502New-style classes are also supported:
503
504 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000505 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000506 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000507 1 SampleNewStyleClass
508 1 SampleNewStyleClass.__init__
509 1 SampleNewStyleClass.double
510 1 SampleNewStyleClass.get
511
512Finding Tests in Modules
513~~~~~~~~~~~~~~~~~~~~~~~~
514For a module, DocTestFinder will create a test for the class's
515docstring, and will recursively explore its contents, including
516functions, classes, and the `__test__` dictionary, if it exists:
517
518 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000519 >>> import types
520 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000521 >>> def triple(val):
522 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000523 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000524 ... 33
525 ... '''
526 ... return val*3
527 >>> m.__dict__.update({
528 ... 'sample_func': sample_func,
529 ... 'SampleClass': SampleClass,
530 ... '__doc__': '''
531 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000532 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000533 ... module
534 ... ''',
535 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000536 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000537 ... 'c': triple}})
538
539 >>> finder = doctest.DocTestFinder()
540 >>> # Use module=test.test_doctest, to prevent doctest from
541 >>> # ignoring the objects since they weren't defined in m.
542 >>> import test.test_doctest
543 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000544 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000545 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000546 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000547 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000548 3 some_module.SampleClass.NestedClass
549 1 some_module.SampleClass.NestedClass.__init__
550 1 some_module.SampleClass.__init__
551 2 some_module.SampleClass.a_classmethod
552 1 some_module.SampleClass.a_property
553 1 some_module.SampleClass.a_staticmethod
554 1 some_module.SampleClass.double
555 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000556 1 some_module.__test__.c
557 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000558 1 some_module.sample_func
559
560Duplicate Removal
561~~~~~~~~~~~~~~~~~
562If a single object is listed twice (under different names), then tests
563will only be generated for it once:
564
Tim Petersf3f57472004-08-08 06:11:48 +0000565 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000566 >>> assert doctest_aliases.TwoNames.f
567 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000568 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000569 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000570 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000571 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000572 test.doctest_aliases.TwoNames
573
574 TwoNames.f and TwoNames.g are bound to the same object.
575 We can't guess which will be found in doctest's traversal of
576 TwoNames.__dict__ first, so we have to allow for either.
577
578 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000579 True
580
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000581Empty Tests
582~~~~~~~~~~~
583By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000584
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000585 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000586 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000587 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000588 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000589 3 SampleClass.NestedClass
590 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000591 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000592 2 SampleClass.a_classmethod
593 1 SampleClass.a_property
594 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000595 1 SampleClass.double
596 1 SampleClass.get
597
598By default, that excluded objects with no doctests. exclude_empty=False
599tells it to include (empty) tests for objects with no doctests. This feature
600is really to support backward compatibility in what doctest.master.summarize()
601displays.
602
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000603 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000604 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000605 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000606 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000607 3 SampleClass.NestedClass
608 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000609 0 SampleClass.NestedClass.get
610 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000611 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000612 2 SampleClass.a_classmethod
613 1 SampleClass.a_property
614 1 SampleClass.a_staticmethod
615 1 SampleClass.double
616 1 SampleClass.get
617
Tim Peters8485b562004-08-04 18:46:34 +0000618Turning off Recursion
619~~~~~~~~~~~~~~~~~~~~~
620DocTestFinder can be told not to look for tests in contained objects
621using the `recurse` flag:
622
623 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000624 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000625 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000626 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000627
628Line numbers
629~~~~~~~~~~~~
630DocTestFinder finds the line number of each example:
631
632 >>> def f(x):
633 ... '''
634 ... >>> x = 12
635 ...
636 ... some text
637 ...
638 ... >>> # examples are not created for comments & bare prompts.
639 ... >>>
640 ... ...
641 ...
642 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000643 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000645 ... >>> x//2
646 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000647 ... '''
648 >>> test = doctest.DocTestFinder().find(f)[0]
649 >>> [e.lineno for e in test.examples]
650 [1, 9, 12]
Zachary Ware7119b452013-11-24 02:21:57 -0600651"""
652
653 if int.__doc__: # simple check for --without-doc-strings, skip if lacking
654 def non_Python_modules(): r"""
Zachary Warea4b7a752013-11-24 01:19:09 -0600655
656Finding Doctests in Modules Not Written in Python
657~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
658DocTestFinder can also find doctests in most modules not written in Python.
659We'll use builtins as an example, since it almost certainly isn't written in
660plain ol' Python and is guaranteed to be available.
661
662 >>> import builtins
663 >>> tests = doctest.DocTestFinder().find(builtins)
INADA Naokia49ac992018-01-27 14:06:21 +0900664 >>> 800 < len(tests) < 820 # approximate number of objects with docstrings
Zachary Ware7119b452013-11-24 02:21:57 -0600665 True
Zachary Warea4b7a752013-11-24 01:19:09 -0600666 >>> real_tests = [t for t in tests if len(t.examples) > 0]
Zachary Ware7119b452013-11-24 02:21:57 -0600667 >>> len(real_tests) # objects that actually have doctests
Lisa Roach5ac70432018-09-13 23:56:23 -0700668 9
Zachary Warea4b7a752013-11-24 01:19:09 -0600669 >>> for t in real_tests:
670 ... print('{} {}'.format(len(t.examples), t.name))
671 ...
672 1 builtins.bin
673 3 builtins.float.as_integer_ratio
674 2 builtins.float.fromhex
675 2 builtins.float.hex
676 1 builtins.hex
677 1 builtins.int
Lisa Roach5ac70432018-09-13 23:56:23 -0700678 3 builtins.int.as_integer_ratio
Zachary Warea4b7a752013-11-24 01:19:09 -0600679 2 builtins.int.bit_length
680 1 builtins.oct
681
682Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
683'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
684and 'int' is a type.
Tim Peters8485b562004-08-04 18:46:34 +0000685"""
686
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500687
688class TestDocTestFinder(unittest.TestCase):
689
690 def test_empty_namespace_package(self):
691 pkg_name = 'doctest_empty_pkg'
Nick Coghland5d9e022018-03-25 23:03:10 +1000692 with tempfile.TemporaryDirectory() as parent_dir:
693 pkg_dir = os.path.join(parent_dir, pkg_name)
694 os.mkdir(pkg_dir)
695 sys.path.append(parent_dir)
696 try:
697 mod = importlib.import_module(pkg_name)
698 finally:
699 support.forget(pkg_name)
700 sys.path.pop()
701 assert doctest.DocTestFinder().find(mod) == []
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500702
703
Edward Loper00f8da72004-08-26 18:05:07 +0000704def test_DocTestParser(): r"""
705Unit tests for the `DocTestParser` class.
706
707DocTestParser is used to parse docstrings containing doctest examples.
708
709The `parse` method divides a docstring into examples and intervening
710text:
711
712 >>> s = '''
713 ... >>> x, y = 2, 3 # no output expected
714 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000715 ... ... print(x)
716 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000717 ... 2
718 ... 3
719 ...
720 ... Some text.
721 ... >>> x+y
722 ... 5
723 ... '''
724 >>> parser = doctest.DocTestParser()
725 >>> for piece in parser.parse(s):
726 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000727 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000728 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000729 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000730 Text: '\n'
731 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
732 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000733 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000734 Text: '\nSome text.\n'
735 Example: ('x+y\n', '5\n', 9)
736 Text: ''
737
738The `get_examples` method returns just the examples:
739
740 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000741 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000742 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000743 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000744 ('x+y\n', '5\n', 9)
745
746The `get_doctest` method creates a Test from the examples, along with the
747given arguments:
748
749 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
750 >>> (test.name, test.filename, test.lineno)
751 ('name', 'filename', 5)
752 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000753 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000754 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000755 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000756 ('x+y\n', '5\n', 9)
757"""
758
Tim Peters8485b562004-08-04 18:46:34 +0000759class test_DocTestRunner:
760 def basics(): r"""
761Unit tests for the `DocTestRunner` class.
762
763DocTestRunner is used to run DocTest test cases, and to accumulate
764statistics. Here's a simple DocTest case we can use:
765
766 >>> def f(x):
767 ... '''
768 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000769 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000770 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000771 ... >>> x//2
772 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000773 ... '''
774 >>> test = doctest.DocTestFinder().find(f)[0]
775
776The main DocTestRunner interface is the `run` method, which runs a
777given DocTest case in a given namespace (globs). It returns a tuple
778`(f,t)`, where `f` is the number of failed tests and `t` is the number
779of tried tests.
780
781 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000782 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000783
784If any example produces incorrect output, then the test runner reports
785the failure and proceeds to the next example:
786
787 >>> def f(x):
788 ... '''
789 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000790 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000791 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000792 ... >>> x//2
793 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000794 ... '''
795 >>> test = doctest.DocTestFinder().find(f)[0]
796 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000797 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000798 Trying:
799 x = 12
800 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000801 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000802 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000803 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000804 Expecting:
805 14
Tim Peters8485b562004-08-04 18:46:34 +0000806 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000807 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000808 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000809 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000810 Expected:
811 14
812 Got:
813 12
Edward Loperaacf0832004-08-26 01:19:50 +0000814 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000815 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000816 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000817 6
Tim Peters8485b562004-08-04 18:46:34 +0000818 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000819 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000820"""
821 def verbose_flag(): r"""
822The `verbose` flag makes the test runner generate more detailed
823output:
824
825 >>> def f(x):
826 ... '''
827 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000828 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000829 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000830 ... >>> x//2
831 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000832 ... '''
833 >>> test = doctest.DocTestFinder().find(f)[0]
834
835 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000836 Trying:
837 x = 12
838 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000839 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000840 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000841 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000842 Expecting:
843 12
Tim Peters8485b562004-08-04 18:46:34 +0000844 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000845 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000846 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000847 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848 6
Tim Peters8485b562004-08-04 18:46:34 +0000849 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000850 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000851
852If the `verbose` flag is unspecified, then the output will be verbose
853iff `-v` appears in sys.argv:
854
855 >>> # Save the real sys.argv list.
856 >>> old_argv = sys.argv
857
858 >>> # If -v does not appear in sys.argv, then output isn't verbose.
859 >>> sys.argv = ['test']
860 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000861 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000862
863 >>> # If -v does appear in sys.argv, then output is verbose.
864 >>> sys.argv = ['test', '-v']
865 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000866 Trying:
867 x = 12
868 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000869 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000870 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000871 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000872 Expecting:
873 12
Tim Peters8485b562004-08-04 18:46:34 +0000874 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000875 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000876 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000877 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000878 6
Tim Peters8485b562004-08-04 18:46:34 +0000879 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000880 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000881
882 >>> # Restore sys.argv
883 >>> sys.argv = old_argv
884
885In the remaining examples, the test runner's verbosity will be
886explicitly set, to ensure that the test behavior is consistent.
887 """
888 def exceptions(): r"""
889Tests of `DocTestRunner`'s exception handling.
890
891An expected exception is specified with a traceback message. The
892lines between the first line and the type/value may be omitted or
893replaced with any other string:
894
895 >>> def f(x):
896 ... '''
897 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000898 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000899 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000900 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000901 ... '''
902 >>> test = doctest.DocTestFinder().find(f)[0]
903 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000904 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000905
Edward Loper19b19582004-08-25 23:07:03 +0000906An example may not generate output before it raises an exception; if
907it does, then the traceback message will not be recognized as
908signaling an expected exception, so the example will be reported as an
909unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000910
911 >>> def f(x):
912 ... '''
913 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000914 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000915 ... pre-exception output
916 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000917 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000918 ... '''
919 >>> test = doctest.DocTestFinder().find(f)[0]
920 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000921 ... # doctest: +ELLIPSIS
922 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000923 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000924 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000925 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000926 Exception raised:
927 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000928 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000929 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000930
931Exception messages may contain newlines:
932
933 >>> def f(x):
934 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000935 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000936 ... Traceback (most recent call last):
937 ... ValueError: multi
938 ... line
939 ... message
940 ... '''
941 >>> test = doctest.DocTestFinder().find(f)[0]
942 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000943 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000944
945If an exception is expected, but an exception with the wrong type or
946message is raised, then it is reported as a failure:
947
948 >>> def f(x):
949 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000950 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000951 ... Traceback (most recent call last):
952 ... ValueError: wrong message
953 ... '''
954 >>> test = doctest.DocTestFinder().find(f)[0]
955 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000956 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000957 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000958 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000959 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000960 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000961 Expected:
962 Traceback (most recent call last):
963 ValueError: wrong message
964 Got:
965 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000966 ...
Tim Peters8485b562004-08-04 18:46:34 +0000967 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000968 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000969
Tim Peters1fbf9c52004-09-04 17:21:02 +0000970However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
971detail:
972
973 >>> def f(x):
974 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000975 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000976 ... Traceback (most recent call last):
977 ... ValueError: wrong message
978 ... '''
979 >>> test = doctest.DocTestFinder().find(f)[0]
980 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000981 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000982
Nick Coghlan5e76e942010-06-12 13:42:46 +0000983IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
984between Python versions. For example, in Python 2.x, the module path of
985the exception is not in the output, but this will fail under Python 3:
986
987 >>> def f(x):
988 ... r'''
989 ... >>> from http.client import HTTPException
990 ... >>> raise HTTPException('message')
991 ... Traceback (most recent call last):
992 ... HTTPException: message
993 ... '''
994 >>> test = doctest.DocTestFinder().find(f)[0]
995 >>> doctest.DocTestRunner(verbose=False).run(test)
996 ... # doctest: +ELLIPSIS
997 **********************************************************************
998 File ..., line 4, in f
999 Failed example:
1000 raise HTTPException('message')
1001 Expected:
1002 Traceback (most recent call last):
1003 HTTPException: message
1004 Got:
1005 Traceback (most recent call last):
1006 ...
1007 http.client.HTTPException: message
1008 TestResults(failed=1, attempted=2)
1009
1010But in Python 3 the module path is included, and therefore a test must look
1011like the following test to succeed in Python 3. But that test will fail under
1012Python 2.
1013
1014 >>> def f(x):
1015 ... r'''
1016 ... >>> from http.client import HTTPException
1017 ... >>> raise HTTPException('message')
1018 ... Traceback (most recent call last):
1019 ... http.client.HTTPException: message
1020 ... '''
1021 >>> test = doctest.DocTestFinder().find(f)[0]
1022 >>> doctest.DocTestRunner(verbose=False).run(test)
1023 TestResults(failed=0, attempted=2)
1024
1025However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1026(or its unexpected absence) will be ignored:
1027
1028 >>> def f(x):
1029 ... r'''
1030 ... >>> from http.client import HTTPException
1031 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1032 ... Traceback (most recent call last):
1033 ... HTTPException: message
1034 ... '''
1035 >>> test = doctest.DocTestFinder().find(f)[0]
1036 >>> doctest.DocTestRunner(verbose=False).run(test)
1037 TestResults(failed=0, attempted=2)
1038
1039The module path will be completely ignored, so two different module paths will
1040still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1041be used when exceptions have changed module.
1042
1043 >>> def f(x):
1044 ... r'''
1045 ... >>> from http.client import HTTPException
1046 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1047 ... Traceback (most recent call last):
1048 ... foo.bar.HTTPException: message
1049 ... '''
1050 >>> test = doctest.DocTestFinder().find(f)[0]
1051 >>> doctest.DocTestRunner(verbose=False).run(test)
1052 TestResults(failed=0, attempted=2)
1053
Tim Peters1fbf9c52004-09-04 17:21:02 +00001054But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1055
1056 >>> def f(x):
1057 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001058 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001059 ... Traceback (most recent call last):
1060 ... TypeError: wrong type
1061 ... '''
1062 >>> test = doctest.DocTestFinder().find(f)[0]
1063 >>> doctest.DocTestRunner(verbose=False).run(test)
1064 ... # doctest: +ELLIPSIS
1065 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001066 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001067 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001068 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001069 Expected:
1070 Traceback (most recent call last):
1071 TypeError: wrong type
1072 Got:
1073 Traceback (most recent call last):
1074 ...
1075 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001076 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001077
Tim Petersf9a07f22013-12-03 21:02:05 -06001078If the exception does not have a message, you can still use
1079IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1080
1081 >>> def f(x):
1082 ... r'''
1083 ... >>> from http.client import HTTPException
1084 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1085 ... Traceback (most recent call last):
1086 ... foo.bar.HTTPException
1087 ... '''
1088 >>> test = doctest.DocTestFinder().find(f)[0]
1089 >>> doctest.DocTestRunner(verbose=False).run(test)
1090 TestResults(failed=0, attempted=2)
1091
1092Note that a trailing colon doesn't matter either:
1093
1094 >>> def f(x):
1095 ... r'''
1096 ... >>> from http.client import HTTPException
1097 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1098 ... Traceback (most recent call last):
1099 ... foo.bar.HTTPException:
1100 ... '''
1101 >>> test = doctest.DocTestFinder().find(f)[0]
1102 >>> doctest.DocTestRunner(verbose=False).run(test)
1103 TestResults(failed=0, attempted=2)
1104
Tim Peters8485b562004-08-04 18:46:34 +00001105If an exception is raised but not expected, then it is reported as an
1106unexpected exception:
1107
Tim Peters8485b562004-08-04 18:46:34 +00001108 >>> def f(x):
1109 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001110 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001111 ... 0
1112 ... '''
1113 >>> test = doctest.DocTestFinder().find(f)[0]
1114 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001115 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001116 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001117 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001118 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001119 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001120 Exception raised:
1121 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001122 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001123 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001124 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001125"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001126 def displayhook(): r"""
1127Test that changing sys.displayhook doesn't matter for doctest.
1128
1129 >>> import sys
1130 >>> orig_displayhook = sys.displayhook
1131 >>> def my_displayhook(x):
1132 ... print('hi!')
1133 >>> sys.displayhook = my_displayhook
1134 >>> def f():
1135 ... '''
1136 ... >>> 3
1137 ... 3
1138 ... '''
1139 >>> test = doctest.DocTestFinder().find(f)[0]
1140 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1141 >>> post_displayhook = sys.displayhook
1142
1143 We need to restore sys.displayhook now, so that we'll be able to test
1144 results.
1145
1146 >>> sys.displayhook = orig_displayhook
1147
1148 Ok, now we can check that everything is ok.
1149
1150 >>> r
1151 TestResults(failed=0, attempted=1)
1152 >>> post_displayhook is my_displayhook
1153 True
1154"""
Tim Peters8485b562004-08-04 18:46:34 +00001155 def optionflags(): r"""
1156Tests of `DocTestRunner`'s option flag handling.
1157
1158Several option flags can be used to customize the behavior of the test
1159runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001160to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001161together).
1162
1163The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1164and 1/0:
1165
1166 >>> def f(x):
1167 ... '>>> True\n1\n'
1168
1169 >>> # Without the flag:
1170 >>> test = doctest.DocTestFinder().find(f)[0]
1171 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001172 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001173
1174 >>> # With the flag:
1175 >>> test = doctest.DocTestFinder().find(f)[0]
1176 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1177 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001178 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001179 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001180 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001181 Failed example:
1182 True
1183 Expected:
1184 1
1185 Got:
1186 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001187 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001188
1189The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1190and the '<BLANKLINE>' marker:
1191
1192 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001193 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001194
1195 >>> # Without the flag:
1196 >>> test = doctest.DocTestFinder().find(f)[0]
1197 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001198 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001199
1200 >>> # With the flag:
1201 >>> test = doctest.DocTestFinder().find(f)[0]
1202 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1203 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001204 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001205 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001206 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001207 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001208 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001209 Expected:
1210 a
1211 <BLANKLINE>
1212 b
1213 Got:
1214 a
1215 <BLANKLINE>
1216 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001217 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001218
1219The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1220treated as equal:
1221
1222 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001223 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001224
1225 >>> # Without the flag:
1226 >>> test = doctest.DocTestFinder().find(f)[0]
1227 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001228 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001229 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001230 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001231 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001232 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001233 Expected:
1234 1 2
1235 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001236 Got:
1237 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001238 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001239
1240 >>> # With the flag:
1241 >>> test = doctest.DocTestFinder().find(f)[0]
1242 >>> flags = doctest.NORMALIZE_WHITESPACE
1243 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001244 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001245
Tim Peters026f8dc2004-08-19 16:38:58 +00001246 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001247 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001248 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1249 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1250
Tim Peters8485b562004-08-04 18:46:34 +00001251The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1252output to match any substring in the actual output:
1253
1254 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001255 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001256
1257 >>> # Without the flag:
1258 >>> test = doctest.DocTestFinder().find(f)[0]
1259 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001260 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001261 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001262 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001263 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001264 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001265 Expected:
1266 [0, 1, 2, ..., 14]
1267 Got:
1268 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001269 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001270
1271 >>> # With the flag:
1272 >>> test = doctest.DocTestFinder().find(f)[0]
1273 >>> flags = doctest.ELLIPSIS
1274 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001275 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001276
Tim Peterse594bee2004-08-22 01:47:51 +00001277 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001278
Guido van Rossume0192e52007-02-09 23:39:59 +00001279 >>> if 1:
1280 ... for i in range(100):
1281 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1282 ... print('!')
1283 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001284
Tim Peters026f8dc2004-08-19 16:38:58 +00001285 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001286
Guido van Rossume0192e52007-02-09 23:39:59 +00001287 >>> if 1: #doctest: +ELLIPSIS
1288 ... for i in range(20):
1289 ... print(i, end=' ')
1290 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001291 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001292
Tim Peters026f8dc2004-08-19 16:38:58 +00001293 Examples from the docs:
1294
Guido van Rossum805365e2007-05-07 22:24:25 +00001295 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001296 [0, 1, ..., 18, 19]
1297
Guido van Rossum805365e2007-05-07 22:24:25 +00001298 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001299 ... # doctest: +NORMALIZE_WHITESPACE
1300 [0, 1, ..., 18, 19]
1301
Thomas Wouters477c8d52006-05-27 19:21:47 +00001302The SKIP flag causes an example to be skipped entirely. I.e., the
1303example is not run. It can be useful in contexts where doctest
1304examples serve as both documentation and test cases, and an example
1305should be included for documentation purposes, but should not be
1306checked (e.g., because its output is random, or depends on resources
1307which would be unavailable.) The SKIP flag can also be used for
1308'commenting out' broken examples.
1309
1310 >>> import unavailable_resource # doctest: +SKIP
1311 >>> unavailable_resource.do_something() # doctest: +SKIP
1312 >>> unavailable_resource.blow_up() # doctest: +SKIP
1313 Traceback (most recent call last):
1314 ...
1315 UncheckedBlowUpError: Nobody checks me.
1316
1317 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001318 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001319 0.721216923889
1320
Edward Loper71f55af2004-08-26 01:41:51 +00001321The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001322and actual outputs to be displayed using a unified diff:
1323
1324 >>> def f(x):
1325 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001326 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001327 ... a
1328 ... B
1329 ... c
1330 ... d
1331 ... f
1332 ... g
1333 ... h
1334 ... '''
1335
1336 >>> # Without the flag:
1337 >>> test = doctest.DocTestFinder().find(f)[0]
1338 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001339 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001340 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001341 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001342 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001343 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001344 Expected:
1345 a
1346 B
1347 c
1348 d
1349 f
1350 g
1351 h
1352 Got:
1353 a
1354 b
1355 c
1356 d
1357 e
1358 f
1359 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001360 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001361
1362 >>> # With the flag:
1363 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001364 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001365 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001366 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001367 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001368 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001369 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001370 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001371 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001372 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001373 a
1374 -B
1375 +b
1376 c
1377 d
1378 +e
1379 f
1380 g
1381 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001382 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001383
Edward Loper71f55af2004-08-26 01:41:51 +00001384The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001385and actual outputs to be displayed using a context diff:
1386
Edward Loper71f55af2004-08-26 01:41:51 +00001387 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001388 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001389 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001390 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001391 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001392 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001393 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001394 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001395 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001396 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001397 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001398 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001399 a
1400 ! B
1401 c
1402 d
1403 f
1404 g
1405 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001406 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001407 a
1408 ! b
1409 c
1410 d
1411 + e
1412 f
1413 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001414 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001415
1416
Edward Loper71f55af2004-08-26 01:41:51 +00001417The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001418used by the popular ndiff.py utility. This does intraline difference
1419marking, as well as interline differences.
1420
1421 >>> def f(x):
1422 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001423 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001424 ... a b c d e f g h i j k 1 m
1425 ... '''
1426 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001427 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001428 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001429 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001430 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001431 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001432 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001433 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001434 Differences (ndiff with -expected +actual):
1435 - a b c d e f g h i j k 1 m
1436 ? ^
1437 + a b c d e f g h i j k l m
1438 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001439 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001440
Ezio Melotti13925002011-03-16 11:05:33 +02001441The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001442failing example:
1443
1444 >>> def f(x):
1445 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001446 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001447 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001448 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001449 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001450 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001451 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001452 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001453 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001454 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001455 ... 500
1456 ... '''
1457 >>> test = doctest.DocTestFinder().find(f)[0]
1458 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1459 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001460 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001461 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001462 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001463 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001464 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001465 Expected:
1466 200
1467 Got:
1468 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001469 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001470
Ezio Melotti13925002011-03-16 11:05:33 +02001471However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001472
1473 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001474 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001475 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001476 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001477 Expecting:
1478 1
1479 ok
1480 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001481 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001482 Expecting:
1483 200
1484 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001485 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001486 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001487 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001488 Expected:
1489 200
1490 Got:
1491 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001492 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001493
R David Murray5a9d7062012-11-21 15:09:21 -05001494The FAIL_FAST flag causes the runner to exit after the first failing example,
1495so subsequent examples are not even attempted:
1496
1497 >>> flags = doctest.FAIL_FAST
1498 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1499 ... # doctest: +ELLIPSIS
1500 **********************************************************************
1501 File ..., line 5, in f
1502 Failed example:
1503 print(2) # first failure
1504 Expected:
1505 200
1506 Got:
1507 2
1508 TestResults(failed=1, attempted=2)
1509
1510Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1511FAIL_FAST only:
1512
1513 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1514 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1515 ... # doctest: +ELLIPSIS
1516 **********************************************************************
1517 File ..., line 5, in f
1518 Failed example:
1519 print(2) # first failure
1520 Expected:
1521 200
1522 Got:
1523 2
1524 TestResults(failed=1, attempted=2)
1525
1526For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1527exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001528
1529 >>> def f(x):
1530 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001531 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001532 ... 1
1533 ... >>> raise ValueError(2) # first failure
1534 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001535 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001536 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001537 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001538 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001539 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001540 ... 500
1541 ... '''
1542 >>> test = doctest.DocTestFinder().find(f)[0]
1543 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1544 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1545 ... # doctest: +ELLIPSIS
1546 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001547 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001548 Failed example:
1549 raise ValueError(2) # first failure
1550 Exception raised:
1551 ...
1552 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001553 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001554 >>> flags = doctest.FAIL_FAST
1555 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1556 ... # doctest: +ELLIPSIS
1557 **********************************************************************
1558 File ..., line 5, in f
1559 Failed example:
1560 raise ValueError(2) # first failure
1561 Exception raised:
1562 ...
1563 ValueError: 2
1564 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001565
Thomas Wouters477c8d52006-05-27 19:21:47 +00001566New option flags can also be registered, via register_optionflag(). Here
1567we reach into doctest's internals a bit.
1568
1569 >>> unlikely = "UNLIKELY_OPTION_NAME"
1570 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1571 False
1572 >>> new_flag_value = doctest.register_optionflag(unlikely)
1573 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1574 True
1575
1576Before 2.4.4/2.5, registering a name more than once erroneously created
1577more than one flag value. Here we verify that's fixed:
1578
1579 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1580 >>> redundant_flag_value == new_flag_value
1581 True
1582
1583Clean up.
1584 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1585
Tim Petersc6cbab02004-08-22 19:43:28 +00001586 """
1587
Tim Peters8485b562004-08-04 18:46:34 +00001588 def option_directives(): r"""
1589Tests of `DocTestRunner`'s option directive mechanism.
1590
Edward Loper74bca7a2004-08-12 02:27:44 +00001591Option directives can be used to turn option flags on or off for a
1592single example. To turn an option on for an example, follow that
1593example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001594
1595 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001596 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001597 ... [0, 1, ..., 9]
1598 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001599 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001600 ... [0, 1, ..., 9]
1601 ... '''
1602 >>> test = doctest.DocTestFinder().find(f)[0]
1603 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001604 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001605 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001606 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001607 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001608 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001609 Expected:
1610 [0, 1, ..., 9]
1611 Got:
1612 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001613 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001614
1615To turn an option off for an example, follow that example with a
1616comment of the form ``# doctest: -OPTION``:
1617
1618 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001619 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001620 ... [0, 1, ..., 9]
1621 ...
1622 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001623 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001624 ... [0, 1, ..., 9]
1625 ... '''
1626 >>> test = doctest.DocTestFinder().find(f)[0]
1627 >>> doctest.DocTestRunner(verbose=False,
1628 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001629 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001630 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001631 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001632 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001633 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001634 Expected:
1635 [0, 1, ..., 9]
1636 Got:
1637 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001638 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001639
1640Option directives affect only the example that they appear with; they
1641do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001642
Edward Loper74bca7a2004-08-12 02:27:44 +00001643 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001644 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001645 ... [0, 1, ..., 9]
1646 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001647 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001648 ... [0, 1, ..., 9]
1649 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001650 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001651 ... [0, 1, ..., 9]
1652 ... '''
1653 >>> test = doctest.DocTestFinder().find(f)[0]
1654 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001655 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001656 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001657 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001658 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001659 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001660 Expected:
1661 [0, 1, ..., 9]
1662 Got:
1663 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001664 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001665 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001666 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001667 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001668 Expected:
1669 [0, 1, ..., 9]
1670 Got:
1671 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001672 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001673
Edward Loper74bca7a2004-08-12 02:27:44 +00001674Multiple options may be modified by a single option directive. They
1675may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001676
1677 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001678 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001679 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001680 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001681 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001682 ... [0, 1, ..., 9]
1683 ... '''
1684 >>> test = doctest.DocTestFinder().find(f)[0]
1685 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001686 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001687 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001688 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001689 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001690 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001691 Expected:
1692 [0, 1, ..., 9]
1693 Got:
1694 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001695 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001696
1697 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001698 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001699 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001700 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001701 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1702 ... [0, 1, ..., 9]
1703 ... '''
1704 >>> test = doctest.DocTestFinder().find(f)[0]
1705 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001706 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001707 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001708 File ..., line 2, 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
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=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001716
1717 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001718 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001719 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001720 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001721 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1722 ... [0, 1, ..., 9]
1723 ... '''
1724 >>> test = doctest.DocTestFinder().find(f)[0]
1725 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001726 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001727 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001728 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001729 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001730 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001731 Expected:
1732 [0, 1, ..., 9]
1733 Got:
1734 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001735 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001736
1737The option directive may be put on the line following the source, as
1738long as a continuation prompt is used:
1739
1740 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001741 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001742 ... ... # doctest: +ELLIPSIS
1743 ... [0, 1, ..., 9]
1744 ... '''
1745 >>> test = doctest.DocTestFinder().find(f)[0]
1746 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001747 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001748
Edward Loper74bca7a2004-08-12 02:27:44 +00001749For examples with multi-line source, the option directive may appear
1750at the end of any line:
1751
1752 >>> def f(x): r'''
1753 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001754 ... ... print(' ', x, end='', sep='')
1755 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001756 ...
1757 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001758 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1759 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001760 ... '''
1761 >>> test = doctest.DocTestFinder().find(f)[0]
1762 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001763 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001764
1765If more than one line of an example with multi-line source has an
1766option directive, then they are combined:
1767
1768 >>> def f(x): r'''
1769 ... Should fail (option directive not on the last line):
1770 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001771 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001772 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001773 ... '''
1774 >>> test = doctest.DocTestFinder().find(f)[0]
1775 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001776 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001777
1778It is an error to have a comment of the form ``# doctest:`` that is
1779*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1780``OPTION`` is an option that has been registered with
1781`register_option`:
1782
1783 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001784 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001785 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1786 Traceback (most recent call last):
1787 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1788
1789 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001790 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001791 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1792 Traceback (most recent call last):
1793 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1794
1795It is an error to use an option directive on a line that contains no
1796source:
1797
1798 >>> s = '>>> # doctest: +ELLIPSIS'
1799 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1800 Traceback (most recent call last):
1801 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 +00001802"""
1803
1804def test_testsource(): r"""
1805Unit tests for `testsource()`.
1806
1807The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001808test with that name in that module, and converts it to a script. The
1809example code is converted to regular Python code. The surrounding
1810words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001811
1812 >>> import test.test_doctest
1813 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001814 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001815 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001816 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001817 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001818 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001819 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001820 #
Edward Lopera5db6002004-08-12 02:41:30 +00001821 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001822 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001823
1824 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001825 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001826 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001827 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001828 ## 1
1829 ## 2
1830 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001831 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001832
1833 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001834 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001835 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001836 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001837 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001838 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001839 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001840 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001841 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001842"""
1843
1844def test_debug(): r"""
1845
1846Create a docstring that we want to debug:
1847
1848 >>> s = '''
1849 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001850 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001851 ... 12
1852 ... '''
1853
1854Create some fake stdin input, to feed to the debugger:
1855
Tim Peters8485b562004-08-04 18:46:34 +00001856 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001857 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001858
1859Run the debugger on the docstring, and then restore sys.stdin.
1860
Edward Loper2de91ba2004-08-27 02:07:46 +00001861 >>> try: doctest.debug_src(s)
1862 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001863 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001864 (Pdb) next
1865 12
Tim Peters8485b562004-08-04 18:46:34 +00001866 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001868 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001869 12
1870 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001871
1872"""
1873
Brett Cannon31f59292011-02-21 19:29:56 +00001874if not hasattr(sys, 'gettrace') or not sys.gettrace():
1875 def test_pdb_set_trace():
1876 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001877
Brett Cannon31f59292011-02-21 19:29:56 +00001878 You can use pdb.set_trace from a doctest. To do so, you must
1879 retrieve the set_trace function from the pdb module at the time
1880 you use it. The doctest module changes sys.stdout so that it can
1881 capture program output. It also temporarily replaces pdb.set_trace
1882 with a version that restores stdout. This is necessary for you to
1883 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001884
Brett Cannon31f59292011-02-21 19:29:56 +00001885 >>> doc = '''
1886 ... >>> x = 42
1887 ... >>> raise Exception('clé')
1888 ... Traceback (most recent call last):
1889 ... Exception: clé
1890 ... >>> import pdb; pdb.set_trace()
1891 ... '''
1892 >>> parser = doctest.DocTestParser()
1893 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1894 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001895
Brett Cannon31f59292011-02-21 19:29:56 +00001896 To demonstrate this, we'll create a fake standard input that
1897 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001898
Brett Cannon31f59292011-02-21 19:29:56 +00001899 >>> real_stdin = sys.stdin
1900 >>> sys.stdin = _FakeInput([
1901 ... 'print(x)', # print data defined by the example
1902 ... 'continue', # stop debugging
1903 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001904
Brett Cannon31f59292011-02-21 19:29:56 +00001905 >>> try: runner.run(test)
1906 ... finally: sys.stdin = real_stdin
1907 --Return--
1908 > <doctest foo-bar@baz[2]>(1)<module>()->None
1909 -> import pdb; pdb.set_trace()
1910 (Pdb) print(x)
1911 42
1912 (Pdb) continue
1913 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001914
Brett Cannon31f59292011-02-21 19:29:56 +00001915 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001916
Brett Cannon31f59292011-02-21 19:29:56 +00001917 >>> def calls_set_trace():
1918 ... y=2
1919 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001920
Brett Cannon31f59292011-02-21 19:29:56 +00001921 >>> doc = '''
1922 ... >>> x=1
1923 ... >>> calls_set_trace()
1924 ... '''
1925 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1926 >>> real_stdin = sys.stdin
1927 >>> sys.stdin = _FakeInput([
1928 ... 'print(y)', # print data defined in the function
1929 ... 'up', # out of function
1930 ... 'print(x)', # print data defined by the example
1931 ... 'continue', # stop debugging
1932 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001933
Brett Cannon31f59292011-02-21 19:29:56 +00001934 >>> try:
1935 ... runner.run(test)
1936 ... finally:
1937 ... sys.stdin = real_stdin
1938 --Return--
Serhiy Storchakae437a102016-04-24 21:41:02 +03001939 > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
Brett Cannon31f59292011-02-21 19:29:56 +00001940 -> import pdb; pdb.set_trace()
1941 (Pdb) print(y)
1942 2
1943 (Pdb) up
1944 > <doctest foo-bar@baz[1]>(1)<module>()
1945 -> calls_set_trace()
1946 (Pdb) print(x)
1947 1
1948 (Pdb) continue
1949 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001950
Brett Cannon31f59292011-02-21 19:29:56 +00001951 During interactive debugging, source code is shown, even for
1952 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001953
Brett Cannon31f59292011-02-21 19:29:56 +00001954 >>> doc = '''
1955 ... >>> def f(x):
1956 ... ... g(x*2)
1957 ... >>> def g(x):
1958 ... ... print(x+3)
1959 ... ... import pdb; pdb.set_trace()
1960 ... >>> f(3)
1961 ... '''
1962 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1963 >>> real_stdin = sys.stdin
1964 >>> sys.stdin = _FakeInput([
1965 ... 'list', # list source from example 2
1966 ... 'next', # return from g()
1967 ... 'list', # list source from example 1
1968 ... 'next', # return from f()
1969 ... 'list', # list source from example 3
1970 ... 'continue', # stop debugging
1971 ... ''])
1972 >>> try: runner.run(test)
1973 ... finally: sys.stdin = real_stdin
1974 ... # doctest: +NORMALIZE_WHITESPACE
1975 --Return--
1976 > <doctest foo-bar@baz[1]>(3)g()->None
1977 -> import pdb; pdb.set_trace()
1978 (Pdb) list
1979 1 def g(x):
1980 2 print(x+3)
1981 3 -> import pdb; pdb.set_trace()
1982 [EOF]
1983 (Pdb) next
1984 --Return--
1985 > <doctest foo-bar@baz[0]>(2)f()->None
1986 -> g(x*2)
1987 (Pdb) list
1988 1 def f(x):
1989 2 -> g(x*2)
1990 [EOF]
1991 (Pdb) next
1992 --Return--
1993 > <doctest foo-bar@baz[2]>(1)<module>()->None
1994 -> f(3)
1995 (Pdb) list
1996 1 -> f(3)
1997 [EOF]
1998 (Pdb) continue
1999 **********************************************************************
2000 File "foo-bar@baz.py", line 7, in foo-bar@baz
2001 Failed example:
2002 f(3)
2003 Expected nothing
2004 Got:
2005 9
2006 TestResults(failed=1, attempted=3)
2007 """
Jim Fulton356fd192004-08-09 11:34:47 +00002008
Brett Cannon31f59292011-02-21 19:29:56 +00002009 def test_pdb_set_trace_nested():
2010 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00002011
Brett Cannon31f59292011-02-21 19:29:56 +00002012 >>> class C(object):
2013 ... def calls_set_trace(self):
2014 ... y = 1
2015 ... import pdb; pdb.set_trace()
2016 ... self.f1()
2017 ... y = 2
2018 ... def f1(self):
2019 ... x = 1
2020 ... self.f2()
2021 ... x = 2
2022 ... def f2(self):
2023 ... z = 1
2024 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002025
Brett Cannon31f59292011-02-21 19:29:56 +00002026 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002027
Brett Cannon31f59292011-02-21 19:29:56 +00002028 >>> doc = '''
2029 ... >>> a = 1
2030 ... >>> calls_set_trace()
2031 ... '''
2032 >>> parser = doctest.DocTestParser()
2033 >>> runner = doctest.DocTestRunner(verbose=False)
2034 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2035 >>> real_stdin = sys.stdin
2036 >>> sys.stdin = _FakeInput([
2037 ... 'print(y)', # print data defined in the function
2038 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2039 ... 'up', 'print(x)',
2040 ... 'up', 'print(y)',
2041 ... 'up', 'print(foo)',
2042 ... 'continue', # stop debugging
2043 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002044
Brett Cannon31f59292011-02-21 19:29:56 +00002045 >>> try:
2046 ... runner.run(test)
2047 ... finally:
2048 ... sys.stdin = real_stdin
2049 ... # doctest: +REPORT_NDIFF
2050 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2051 -> self.f1()
2052 (Pdb) print(y)
2053 1
2054 (Pdb) step
2055 --Call--
2056 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2057 -> def f1(self):
2058 (Pdb) step
2059 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2060 -> x = 1
2061 (Pdb) step
2062 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2063 -> self.f2()
2064 (Pdb) step
2065 --Call--
2066 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2067 -> def f2(self):
2068 (Pdb) step
2069 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2070 -> z = 1
2071 (Pdb) step
2072 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2073 -> z = 2
2074 (Pdb) print(z)
2075 1
2076 (Pdb) up
2077 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2078 -> self.f2()
2079 (Pdb) print(x)
2080 1
2081 (Pdb) up
2082 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2083 -> self.f1()
2084 (Pdb) print(y)
2085 1
2086 (Pdb) up
2087 > <doctest foo-bar@baz[1]>(1)<module>()
2088 -> calls_set_trace()
2089 (Pdb) print(foo)
2090 *** NameError: name 'foo' is not defined
2091 (Pdb) continue
2092 TestResults(failed=0, attempted=2)
2093 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002094
Tim Peters19397e52004-08-06 22:02:59 +00002095def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002096 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002097
2098 We create a Suite by providing a module. A module can be provided
2099 by passing a module object:
2100
2101 >>> import unittest
2102 >>> import test.sample_doctest
2103 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2104 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002105 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002106
2107 We can also supply the module by name:
2108
2109 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2110 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002111 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002112
R David Murray5abd76a2012-09-10 10:15:58 -04002113 The module need not contain any doctest examples:
2114
2115 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2116 >>> suite.run(unittest.TestResult())
2117 <unittest.result.TestResult run=0 errors=0 failures=0>
2118
R David Murray1976d9b2014-04-14 20:28:36 -04002119 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002120
R David Murray1976d9b2014-04-14 20:28:36 -04002121 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002122 >>> suite.run(unittest.TestResult())
2123 <unittest.result.TestResult run=0 errors=0 failures=0>
2124
Tim Peters19397e52004-08-06 22:02:59 +00002125 We can use the current module:
2126
2127 >>> suite = test.sample_doctest.test_suite()
2128 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002129 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002130
R David Murray1976d9b2014-04-14 20:28:36 -04002131 We can also provide a DocTestFinder:
2132
2133 >>> finder = doctest.DocTestFinder()
2134 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2135 ... test_finder=finder)
2136 >>> suite.run(unittest.TestResult())
2137 <unittest.result.TestResult run=9 errors=0 failures=4>
2138
2139 The DocTestFinder need not return any tests:
2140
2141 >>> finder = doctest.DocTestFinder()
2142 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2143 ... test_finder=finder)
2144 >>> suite.run(unittest.TestResult())
2145 <unittest.result.TestResult run=0 errors=0 failures=0>
2146
Tim Peters19397e52004-08-06 22:02:59 +00002147 We can supply global variables. If we pass globs, they will be
2148 used instead of the module globals. Here we'll pass an empty
2149 globals, triggering an extra error:
2150
2151 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2152 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002153 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002154
2155 Alternatively, we can provide extra globals. Here we'll make an
2156 error go away by providing an extra global variable:
2157
2158 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2159 ... extraglobs={'y': 1})
2160 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002161 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002162
2163 You can pass option flags. Here we'll cause an extra error
2164 by disabling the blank-line feature:
2165
2166 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002167 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002168 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002169 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002170
Tim Peters1e277ee2004-08-07 05:37:52 +00002171 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002172
Jim Fultonf54bad42004-08-28 14:57:56 +00002173 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002174 ... import test.test_doctest
2175 ... test.test_doctest.sillySetup = True
2176
Jim Fultonf54bad42004-08-28 14:57:56 +00002177 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002178 ... import test.test_doctest
2179 ... del test.test_doctest.sillySetup
2180
2181 Here, we installed a silly variable that the test expects:
2182
2183 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2184 ... setUp=setUp, tearDown=tearDown)
2185 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002186 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002187
2188 But the tearDown restores sanity:
2189
2190 >>> import test.test_doctest
2191 >>> test.test_doctest.sillySetup
2192 Traceback (most recent call last):
2193 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002194 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002195
Berker Peksag4882cac2015-04-14 09:30:01 +03002196 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002197 we'll use the setUp function to supply the missing variable y:
2198
2199 >>> def setUp(test):
2200 ... test.globs['y'] = 1
2201
2202 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2203 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002204 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002205
2206 Here, we didn't need to use a tearDown function because we
2207 modified the test globals, which are a copy of the
2208 sample_doctest module dictionary. The test globals are
2209 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002210 """
2211
2212def test_DocFileSuite():
2213 """We can test tests found in text files using a DocFileSuite.
2214
2215 We create a suite by providing the names of one or more text
2216 files that include examples:
2217
2218 >>> import unittest
2219 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002220 ... 'test_doctest2.txt',
2221 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002222 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002223 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002224
2225 The test files are looked for in the directory containing the
2226 calling module. A package keyword argument can be provided to
2227 specify a different relative location.
2228
2229 >>> import unittest
2230 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2231 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002232 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002233 ... package='test')
2234 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002235 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002236
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002237 Support for using a package's __loader__.get_data() is also
2238 provided.
2239
2240 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002241 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002242 >>> if not hasattr(test, '__loader__'):
2243 ... test.__loader__ = pkgutil.get_loader(test)
2244 ... added_loader = True
2245 >>> try:
2246 ... suite = doctest.DocFileSuite('test_doctest.txt',
2247 ... 'test_doctest2.txt',
2248 ... 'test_doctest4.txt',
2249 ... package='test')
2250 ... suite.run(unittest.TestResult())
2251 ... finally:
2252 ... if added_loader:
2253 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002254 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002255
Edward Loper0273f5b2004-09-18 20:27:04 +00002256 '/' should be used as a path separator. It will be converted
2257 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002258
2259 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2260 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002261 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002262
Edward Loper0273f5b2004-09-18 20:27:04 +00002263 If DocFileSuite is used from an interactive session, then files
2264 are resolved relative to the directory of sys.argv[0]:
2265
Christian Heimes45f9af32007-11-27 21:50:00 +00002266 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002267 >>> save_argv = sys.argv
2268 >>> sys.argv = [test.test_doctest.__file__]
2269 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002270 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002271 >>> sys.argv = save_argv
2272
Edward Loper052d0cd2004-09-19 17:19:33 +00002273 By setting `module_relative=False`, os-specific paths may be
2274 used (including absolute paths and paths relative to the
2275 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002276
2277 >>> # Get the absolute path of the test package.
2278 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2279 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2280
2281 >>> # Use it to find the absolute path of test_doctest.txt.
2282 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2283
Edward Loper052d0cd2004-09-19 17:19:33 +00002284 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002285 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002286 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002287
Edward Loper052d0cd2004-09-19 17:19:33 +00002288 It is an error to specify `package` when `module_relative=False`:
2289
2290 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2291 ... package='test')
2292 Traceback (most recent call last):
2293 ValueError: Package may only be specified for module-relative paths.
2294
Tim Peters19397e52004-08-06 22:02:59 +00002295 You can specify initial global variables:
2296
2297 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2298 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002299 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002300 ... globs={'favorite_color': 'blue'})
2301 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002302 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002303
2304 In this case, we supplied a missing favorite color. You can
2305 provide doctest options:
2306
2307 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2308 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002309 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002310 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2311 ... globs={'favorite_color': 'blue'})
2312 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002313 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002314
2315 And, you can provide setUp and tearDown functions:
2316
Jim Fultonf54bad42004-08-28 14:57:56 +00002317 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002318 ... import test.test_doctest
2319 ... test.test_doctest.sillySetup = True
2320
Jim Fultonf54bad42004-08-28 14:57:56 +00002321 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002322 ... import test.test_doctest
2323 ... del test.test_doctest.sillySetup
2324
2325 Here, we installed a silly variable that the test expects:
2326
2327 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2328 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002329 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002330 ... setUp=setUp, tearDown=tearDown)
2331 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002332 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002333
2334 But the tearDown restores sanity:
2335
2336 >>> import test.test_doctest
2337 >>> test.test_doctest.sillySetup
2338 Traceback (most recent call last):
2339 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002340 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002341
Berker Peksag4882cac2015-04-14 09:30:01 +03002342 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002343 Here, we'll use a setUp function to set the favorite color in
2344 test_doctest.txt:
2345
2346 >>> def setUp(test):
2347 ... test.globs['favorite_color'] = 'blue'
2348
2349 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2350 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002351 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002352
2353 Here, we didn't need to use a tearDown function because we
2354 modified the test globals. The test globals are
2355 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002356
Fred Drake7c404a42004-12-21 23:46:34 +00002357 Tests in a file run using `DocFileSuite` can also access the
2358 `__file__` global, which is set to the name of the file
2359 containing the tests:
2360
Benjamin Petersonab078e92016-07-13 21:13:29 -07002361 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
Fred Drake7c404a42004-12-21 23:46:34 +00002362 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002363 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002364
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002365 If the tests contain non-ASCII characters, we have to specify which
2366 encoding the file is encoded with. We do so by using the `encoding`
2367 parameter:
2368
2369 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2370 ... 'test_doctest2.txt',
2371 ... 'test_doctest4.txt',
2372 ... encoding='utf-8')
2373 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002374 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002375
Jim Fultonf54bad42004-08-28 14:57:56 +00002376 """
Tim Peters19397e52004-08-06 22:02:59 +00002377
Jim Fulton07a349c2004-08-22 14:10:00 +00002378def test_trailing_space_in_test():
2379 """
Tim Petersa7def722004-08-23 22:13:22 +00002380 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002381
Jim Fulton07a349c2004-08-22 14:10:00 +00002382 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002383 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002384 foo \n
2385 """
Tim Peters19397e52004-08-06 22:02:59 +00002386
Yury Selivanovb532df62014-12-08 15:00:05 -05002387class Wrapper:
2388 def __init__(self, func):
2389 self.func = func
2390 functools.update_wrapper(self, func)
2391
2392 def __call__(self, *args, **kwargs):
2393 self.func(*args, **kwargs)
2394
2395@Wrapper
2396def test_look_in_unwrapped():
2397 """
2398 Docstrings in wrapped functions must be detected as well.
2399
2400 >>> 'one other test'
2401 'one other test'
2402 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002403
2404def test_unittest_reportflags():
2405 """Default unittest reporting flags can be set to control reporting
2406
2407 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2408 only the first failure of each test. First, we'll look at the
2409 output without the flag. The file test_doctest.txt file has two
2410 tests. They both fail if blank lines are disabled:
2411
2412 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2413 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2414 >>> import unittest
2415 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002416 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002417 Traceback ...
2418 Failed example:
2419 favorite_color
2420 ...
2421 Failed example:
2422 if 1:
2423 ...
2424
2425 Note that we see both failures displayed.
2426
2427 >>> old = doctest.set_unittest_reportflags(
2428 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2429
2430 Now, when we run the test:
2431
2432 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002433 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002434 Traceback ...
2435 Failed example:
2436 favorite_color
2437 Exception raised:
2438 ...
2439 NameError: name 'favorite_color' is not defined
2440 <BLANKLINE>
2441 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002442
Jim Fultonf54bad42004-08-28 14:57:56 +00002443 We get only the first failure.
2444
2445 If we give any reporting options when we set up the tests,
2446 however:
2447
2448 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2449 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2450
2451 Then the default eporting options are ignored:
2452
2453 >>> result = suite.run(unittest.TestResult())
Pablo Galindoc5dc60e2019-01-10 14:29:40 +00002454
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302455 *NOTE*: These doctest are intentionally not placed in raw string to depict
2456 the trailing whitespace using `\x20` in the diff below.
2457
Guido van Rossum7131f842007-02-09 20:13:25 +00002458 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002459 Traceback ...
2460 Failed example:
2461 favorite_color
2462 ...
2463 Failed example:
2464 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002465 print('a')
2466 print()
2467 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002468 Differences (ndiff with -expected +actual):
2469 a
2470 - <BLANKLINE>
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302471 +\x20
Jim Fultonf54bad42004-08-28 14:57:56 +00002472 b
2473 <BLANKLINE>
2474 <BLANKLINE>
2475
2476
2477 Test runners can restore the formatting flags after they run:
2478
2479 >>> ignored = doctest.set_unittest_reportflags(old)
2480
2481 """
2482
Edward Loper052d0cd2004-09-19 17:19:33 +00002483def test_testfile(): r"""
2484Tests for the `testfile()` function. This function runs all the
2485doctest examples in a given file. In its simple invokation, it is
2486called with the name of a file, which is taken to be relative to the
2487calling module. The return value is (#failures, #tests).
2488
Florent Xicluna59250852010-02-27 14:21:57 +00002489We don't want `-v` in sys.argv for these tests.
2490
2491 >>> save_argv = sys.argv
2492 >>> if '-v' in sys.argv:
2493 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2494
2495
Edward Loper052d0cd2004-09-19 17:19:33 +00002496 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2497 **********************************************************************
2498 File "...", line 6, in test_doctest.txt
2499 Failed example:
2500 favorite_color
2501 Exception raised:
2502 ...
2503 NameError: name 'favorite_color' is not defined
2504 **********************************************************************
2505 1 items had failures:
2506 1 of 2 in test_doctest.txt
2507 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002508 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002509 >>> doctest.master = None # Reset master.
2510
2511(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002512`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002513same name.)
2514
2515Globals may be specified with the `globs` and `extraglobs` parameters:
2516
2517 >>> globs = {'favorite_color': 'blue'}
2518 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002519 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002520 >>> doctest.master = None # Reset master.
2521
2522 >>> extraglobs = {'favorite_color': 'red'}
2523 >>> doctest.testfile('test_doctest.txt', globs=globs,
2524 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2525 **********************************************************************
2526 File "...", line 6, in test_doctest.txt
2527 Failed example:
2528 favorite_color
2529 Expected:
2530 'blue'
2531 Got:
2532 'red'
2533 **********************************************************************
2534 1 items had failures:
2535 1 of 2 in test_doctest.txt
2536 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002537 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002538 >>> doctest.master = None # Reset master.
2539
2540The file may be made relative to a given module or package, using the
2541optional `module_relative` parameter:
2542
2543 >>> doctest.testfile('test_doctest.txt', globs=globs,
2544 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002545 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002546 >>> doctest.master = None # Reset master.
2547
Ezio Melotti13925002011-03-16 11:05:33 +02002548Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002549
2550 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2551 Trying:
2552 favorite_color
2553 Expecting:
2554 'blue'
2555 ok
2556 Trying:
2557 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002558 print('a')
2559 print()
2560 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002561 Expecting:
2562 a
2563 <BLANKLINE>
2564 b
2565 ok
2566 1 items passed all tests:
2567 2 tests in test_doctest.txt
2568 2 tests in 1 items.
2569 2 passed and 0 failed.
2570 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002571 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002572 >>> doctest.master = None # Reset master.
2573
2574The name of the test may be specified with the optional `name`
2575parameter:
2576
2577 >>> doctest.testfile('test_doctest.txt', name='newname')
2578 ... # doctest: +ELLIPSIS
2579 **********************************************************************
2580 File "...", line 6, in newname
2581 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002582 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002583 >>> doctest.master = None # Reset master.
2584
Ezio Melotti13925002011-03-16 11:05:33 +02002585The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002586parameter:
2587
2588 >>> doctest.testfile('test_doctest.txt', report=False)
2589 ... # doctest: +ELLIPSIS
2590 **********************************************************************
2591 File "...", line 6, in test_doctest.txt
2592 Failed example:
2593 favorite_color
2594 Exception raised:
2595 ...
2596 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002597 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002598 >>> doctest.master = None # Reset master.
2599
2600The optional keyword argument `raise_on_error` can be used to raise an
2601exception on the first error (which may be useful for postmortem
2602debugging):
2603
2604 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2605 ... # doctest: +ELLIPSIS
2606 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002607 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002608 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002609
2610If the tests contain non-ASCII characters, the tests might fail, since
2611it's unknown which encoding is used. The encoding can be specified
2612using the optional keyword argument `encoding`:
2613
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002614 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002615 **********************************************************************
2616 File "...", line 7, in test_doctest4.txt
2617 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002618 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002619 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002620 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002621 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002622 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002623 **********************************************************************
2624 ...
2625 **********************************************************************
2626 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002627 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002628 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002629 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002630 >>> doctest.master = None # Reset master.
2631
2632 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002633 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002634 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002635
2636Test the verbose output:
2637
2638 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2639 Trying:
2640 'föö'
2641 Expecting:
2642 'f\xf6\xf6'
2643 ok
2644 Trying:
2645 'bÄ…r'
2646 Expecting:
2647 'b\u0105r'
2648 ok
2649 1 items passed all tests:
2650 2 tests in test_doctest4.txt
2651 2 tests in 1 items.
2652 2 passed and 0 failed.
2653 Test passed.
2654 TestResults(failed=0, attempted=2)
2655 >>> doctest.master = None # Reset master.
2656 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002657"""
2658
R David Murrayb48cb292014-10-02 22:42:42 -04002659def test_lineendings(): r"""
2660*nix systems use \n line endings, while Windows systems use \r\n. Python
2661handles this using universal newline mode for reading files. Let's make
2662sure doctest does so (issue 8473) by creating temporary test files using each
2663of the two line disciplines. One of the two will be the "wrong" one for the
2664platform the test is run on.
2665
2666Windows line endings first:
2667
2668 >>> import tempfile, os
2669 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002670 >>> with open(fn, 'wb') as f:
2671 ... 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 -04002672 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002673 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002674 TestResults(failed=0, attempted=1)
2675 >>> os.remove(fn)
2676
2677And now *nix line endings:
2678
2679 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002680 >>> with open(fn, 'wb') as f:
2681 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002682 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002683 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002684 TestResults(failed=0, attempted=1)
2685 >>> os.remove(fn)
2686
2687"""
2688
R. David Murray58641de2009-06-12 15:33:19 +00002689def test_testmod(): r"""
2690Tests for the testmod function. More might be useful, but for now we're just
2691testing the case raised by Issue 6195, where trying to doctest a C module would
2692fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2693out of the binary module.
2694
2695 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002696 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002697 TestResults(failed=0, attempted=0)
2698"""
2699
Victor Stinner9d396392010-10-16 21:54:59 +00002700try:
2701 os.fsencode("foo-bär@baz.py")
2702except UnicodeEncodeError:
2703 # Skip the test: the filesystem encoding is unable to encode the filename
2704 pass
2705else:
2706 def test_unicode(): """
2707Check doctest with a non-ascii filename:
2708
2709 >>> doc = '''
2710 ... >>> raise Exception('clé')
2711 ... '''
2712 ...
2713 >>> parser = doctest.DocTestParser()
2714 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2715 >>> test
2716 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2717 >>> runner = doctest.DocTestRunner(verbose=False)
2718 >>> runner.run(test) # doctest: +ELLIPSIS
2719 **********************************************************************
2720 File "foo-bär@baz.py", line 2, in foo-bär@baz
2721 Failed example:
2722 raise Exception('clé')
2723 Exception raised:
2724 Traceback (most recent call last):
2725 File ...
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03002726 exec(compile(example.source, filename, "single",
Victor Stinner9d396392010-10-16 21:54:59 +00002727 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2728 raise Exception('clé')
2729 Exception: clé
2730 TestResults(failed=1, attempted=1)
2731 """
2732
R David Murray5707d502013-06-23 14:24:13 -04002733def test_CLI(): r"""
2734The doctest module can be used to run doctests against an arbitrary file.
2735These tests test this CLI functionality.
2736
2737We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002738to a temp dir to run the command against. Due to a current limitation in
2739script_helpers, though, we need a little utility function to turn the returned
2740output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002741
R David Murray4af68982013-06-25 08:11:22 -04002742 >>> def normalize(s):
2743 ... return '\n'.join(s.decode().splitlines())
2744
R David Murray4af68982013-06-25 08:11:22 -04002745With those preliminaries out of the way, we'll start with a file with two
2746simple tests and no errors. We'll run both the unadorned doctest command, and
2747the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002748
Berker Peksagce643912015-05-06 06:33:17 +03002749 >>> from test.support import script_helper, temp_dir
2750 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002751 ... fn = os.path.join(tmpdir, 'myfile.doc')
2752 ... with open(fn, 'w') as f:
2753 ... _ = f.write('This is a very simple test file.\n')
2754 ... _ = f.write(' >>> 1 + 1\n')
2755 ... _ = f.write(' 2\n')
2756 ... _ = f.write(' >>> "a"\n')
2757 ... _ = f.write(" 'a'\n")
2758 ... _ = f.write('\n')
2759 ... _ = f.write('And that is it.\n')
2760 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002761 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002762 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002763 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002764
2765With no arguments and passing tests, we should get no output:
2766
2767 >>> rc1, out1, err1
2768 (0, b'', b'')
2769
2770With the verbose flag, we should see the test output, but no error output:
2771
2772 >>> rc2, err2
2773 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002774 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002775 Trying:
2776 1 + 1
2777 Expecting:
2778 2
2779 ok
2780 Trying:
2781 "a"
2782 Expecting:
2783 'a'
2784 ok
2785 1 items passed all tests:
2786 2 tests in myfile.doc
2787 2 tests in 1 items.
2788 2 passed and 0 failed.
2789 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002790
2791Now we'll write a couple files, one with three tests, the other a python module
2792with two tests, both of the files having "errors" in the tests that can be made
2793non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2794the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002795allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002796ability to process more than one file on the command line and, since the second
2797file ends in '.py', its handling of python module files (as opposed to straight
2798text files).
2799
Berker Peksagce643912015-05-06 06:33:17 +03002800 >>> from test.support import script_helper, temp_dir
2801 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002802 ... fn = os.path.join(tmpdir, 'myfile.doc')
2803 ... with open(fn, 'w') as f:
2804 ... _ = f.write('This is another simple test file.\n')
2805 ... _ = f.write(' >>> 1 + 1\n')
2806 ... _ = f.write(' 2\n')
2807 ... _ = f.write(' >>> "abcdef"\n')
2808 ... _ = f.write(" 'a...f'\n")
2809 ... _ = f.write(' >>> "ajkml"\n')
2810 ... _ = f.write(" 'a...l'\n")
2811 ... _ = f.write('\n')
2812 ... _ = f.write('And that is it.\n')
2813 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2814 ... with open(fn2, 'w') as f:
2815 ... _ = f.write('def test_func():\n')
2816 ... _ = f.write(' \"\"\"\n')
2817 ... _ = f.write(' This is simple python test function.\n')
2818 ... _ = f.write(' >>> 1 + 1\n')
2819 ... _ = f.write(' 2\n')
2820 ... _ = f.write(' >>> "abc def"\n')
2821 ... _ = f.write(" 'abc def'\n")
2822 ... _ = f.write("\n")
2823 ... _ = f.write(' \"\"\"\n')
R David Murray5707d502013-06-23 14:24:13 -04002824 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002825 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002826 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002827 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002828 ... rc3, out3, err3 = script_helper.assert_python_ok(
2829 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002830 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002831 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002832 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002833 ... rc5, out5, err5 = script_helper.assert_python_ok(
2834 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002835 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002836
2837Our first test run will show the errors from the first file (doctest stops if a
2838file has errors). Note that doctest test-run error output appears on stdout,
2839not stderr:
2840
2841 >>> rc1, err1
2842 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002843 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002844 **********************************************************************
2845 File "...myfile.doc", line 4, in myfile.doc
2846 Failed example:
2847 "abcdef"
2848 Expected:
2849 'a...f'
2850 Got:
2851 'abcdef'
2852 **********************************************************************
2853 File "...myfile.doc", line 6, in myfile.doc
2854 Failed example:
2855 "ajkml"
2856 Expected:
2857 'a...l'
2858 Got:
2859 'ajkml'
2860 **********************************************************************
2861 1 items had failures:
2862 2 of 3 in myfile.doc
2863 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002864
2865With -o ELLIPSIS specified, the second run, against just the first file, should
2866produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2867should the third, which ran against both files:
2868
2869 >>> rc2, out2, err2
2870 (0, b'', b'')
2871 >>> rc3, out3, err3
2872 (0, b'', b'')
2873
2874The fourth run uses FAIL_FAST, so we should see only one error:
2875
2876 >>> rc4, err4
2877 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002878 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002879 **********************************************************************
2880 File "...myfile.doc", line 4, in myfile.doc
2881 Failed example:
2882 "abcdef"
2883 Expected:
2884 'a...f'
2885 Got:
2886 'abcdef'
2887 **********************************************************************
2888 1 items had failures:
2889 1 of 2 in myfile.doc
2890 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002891
2892The fifth test uses verbose with the two options, so we should get verbose
2893success output for the tests in both files:
2894
2895 >>> rc5, err5
2896 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002897 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002898 Trying:
2899 1 + 1
2900 Expecting:
2901 2
2902 ok
2903 Trying:
2904 "abcdef"
2905 Expecting:
2906 'a...f'
2907 ok
2908 Trying:
2909 "ajkml"
2910 Expecting:
2911 'a...l'
2912 ok
2913 1 items passed all tests:
2914 3 tests in myfile.doc
2915 3 tests in 1 items.
2916 3 passed and 0 failed.
2917 Test passed.
2918 Trying:
2919 1 + 1
2920 Expecting:
2921 2
2922 ok
2923 Trying:
2924 "abc def"
2925 Expecting:
2926 'abc def'
2927 ok
2928 1 items had no tests:
2929 myfile2
2930 1 items passed all tests:
2931 2 tests in myfile2.test_func
2932 2 tests in 2 items.
2933 2 passed and 0 failed.
2934 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002935
2936We should also check some typical error cases.
2937
2938Invalid file name:
2939
2940 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002941 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04002942 >>> rc, out
2943 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002944 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002945 Traceback (most recent call last):
2946 ...
2947 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
2948
2949Invalid doctest option:
2950
2951 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002952 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04002953 >>> rc, out
2954 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04002955 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002956 usage...invalid...nosuchoption...
2957
2958"""
2959
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302960def test_no_trailing_whitespace_stripping():
2961 r"""
2962 The fancy reports had a bug for a long time where any trailing whitespace on
2963 the reported diff lines was stripped, making it impossible to see the
2964 differences in line reported as different that differed only in the amount of
2965 trailing whitespace. The whitespace still isn't particularly visible unless
2966 you use NDIFF, but at least it is now there to be found.
2967
2968 *NOTE*: This snippet was intentionally put inside a raw string to get rid of
2969 leading whitespace error in executing the example below
2970
2971 >>> def f(x):
2972 ... r'''
2973 ... >>> print('\n'.join(['a ', 'b']))
2974 ... a
2975 ... b
2976 ... '''
2977 """
2978 """
2979 *NOTE*: These doctest are not placed in raw string to depict the trailing whitespace
2980 using `\x20`
2981
2982 >>> test = doctest.DocTestFinder().find(f)[0]
2983 >>> flags = doctest.REPORT_NDIFF
2984 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
2985 ... # doctest: +ELLIPSIS
2986 **********************************************************************
2987 File ..., line 3, in f
2988 Failed example:
2989 print('\n'.join(['a ', 'b']))
2990 Differences (ndiff with -expected +actual):
2991 - a
2992 + a
2993 b
2994 TestResults(failed=1, attempted=1)
2995
2996 *NOTE*: `\x20` is for checking the trailing whitespace on the +a line above.
2997 We cannot use actual spaces there, as a commit hook prevents from committing
2998 patches that contain trailing whitespace. More info on Issue 24746.
2999 """
3000
Tim Peters8485b562004-08-04 18:46:34 +00003001######################################################################
3002## Main
3003######################################################################
3004
3005def test_main():
3006 # Check the doctest cases in doctest itself:
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02003007 ret = support.run_doctest(doctest, verbosity=True)
Victor Stinner931602a2016-03-25 12:48:17 +01003008
Tim Peters8485b562004-08-04 18:46:34 +00003009 # Check the doctest cases defined here:
3010 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003011 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00003012
Jason R. Coombsb9650a02018-03-05 18:29:08 -05003013 # Run unittests
3014 support.run_unittest(__name__)
3015
3016
Tim Peters8485b562004-08-04 18:46:34 +00003017def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00003018 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01003019 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00003020 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00003021 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00003022 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003023 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00003024 r.write_results(show_missing=True, summary=True,
3025 coverdir=coverdir)
3026
3027if __name__ == '__main__':
3028 if '-c' in sys.argv:
3029 test_coverage('/tmp/doctest.cover')
3030 else:
3031 test_main()