blob: 5ea18f52c4fcf2060ba0a30b0e6e8ca16da33bb6 [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
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700668 12
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
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700673 5 builtins.bytearray.hex
674 5 builtins.bytes.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600675 3 builtins.float.as_integer_ratio
676 2 builtins.float.fromhex
677 2 builtins.float.hex
678 1 builtins.hex
679 1 builtins.int
Lisa Roach5ac70432018-09-13 23:56:23 -0700680 3 builtins.int.as_integer_ratio
Zachary Warea4b7a752013-11-24 01:19:09 -0600681 2 builtins.int.bit_length
Gregory P. Smith0c2f9302019-05-29 11:46:58 -0700682 5 builtins.memoryview.hex
Zachary Warea4b7a752013-11-24 01:19:09 -0600683 1 builtins.oct
684
685Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
686'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
687and 'int' is a type.
Tim Peters8485b562004-08-04 18:46:34 +0000688"""
689
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500690
691class TestDocTestFinder(unittest.TestCase):
692
693 def test_empty_namespace_package(self):
694 pkg_name = 'doctest_empty_pkg'
Nick Coghland5d9e022018-03-25 23:03:10 +1000695 with tempfile.TemporaryDirectory() as parent_dir:
696 pkg_dir = os.path.join(parent_dir, pkg_name)
697 os.mkdir(pkg_dir)
698 sys.path.append(parent_dir)
699 try:
700 mod = importlib.import_module(pkg_name)
701 finally:
702 support.forget(pkg_name)
703 sys.path.pop()
704 assert doctest.DocTestFinder().find(mod) == []
Jason R. Coombsb9650a02018-03-05 18:29:08 -0500705
706
Edward Loper00f8da72004-08-26 18:05:07 +0000707def test_DocTestParser(): r"""
708Unit tests for the `DocTestParser` class.
709
710DocTestParser is used to parse docstrings containing doctest examples.
711
712The `parse` method divides a docstring into examples and intervening
713text:
714
715 >>> s = '''
716 ... >>> x, y = 2, 3 # no output expected
717 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000718 ... ... print(x)
719 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000720 ... 2
721 ... 3
722 ...
723 ... Some text.
724 ... >>> x+y
725 ... 5
726 ... '''
727 >>> parser = doctest.DocTestParser()
728 >>> for piece in parser.parse(s):
729 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000730 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000731 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000732 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000733 Text: '\n'
734 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
735 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000736 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000737 Text: '\nSome text.\n'
738 Example: ('x+y\n', '5\n', 9)
739 Text: ''
740
741The `get_examples` method returns just the examples:
742
743 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000744 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000745 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000746 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000747 ('x+y\n', '5\n', 9)
748
749The `get_doctest` method creates a Test from the examples, along with the
750given arguments:
751
752 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
753 >>> (test.name, test.filename, test.lineno)
754 ('name', 'filename', 5)
755 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000756 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000757 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000758 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000759 ('x+y\n', '5\n', 9)
760"""
761
Tim Peters8485b562004-08-04 18:46:34 +0000762class test_DocTestRunner:
763 def basics(): r"""
764Unit tests for the `DocTestRunner` class.
765
766DocTestRunner is used to run DocTest test cases, and to accumulate
767statistics. Here's a simple DocTest case we can use:
768
769 >>> def f(x):
770 ... '''
771 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000772 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000773 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000774 ... >>> x//2
775 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000776 ... '''
777 >>> test = doctest.DocTestFinder().find(f)[0]
778
779The main DocTestRunner interface is the `run` method, which runs a
780given DocTest case in a given namespace (globs). It returns a tuple
781`(f,t)`, where `f` is the number of failed tests and `t` is the number
782of tried tests.
783
784 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000785 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000786
787If any example produces incorrect output, then the test runner reports
788the failure and proceeds to the next example:
789
790 >>> def f(x):
791 ... '''
792 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000793 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000794 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000795 ... >>> x//2
796 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000797 ... '''
798 >>> test = doctest.DocTestFinder().find(f)[0]
799 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000800 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000801 Trying:
802 x = 12
803 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000804 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000805 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000806 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000807 Expecting:
808 14
Tim Peters8485b562004-08-04 18:46:34 +0000809 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000810 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000811 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000812 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000813 Expected:
814 14
815 Got:
816 12
Edward Loperaacf0832004-08-26 01:19:50 +0000817 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000818 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000819 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000820 6
Tim Peters8485b562004-08-04 18:46:34 +0000821 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000822 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000823"""
824 def verbose_flag(): r"""
825The `verbose` flag makes the test runner generate more detailed
826output:
827
828 >>> def f(x):
829 ... '''
830 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000831 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000832 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000833 ... >>> x//2
834 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000835 ... '''
836 >>> test = doctest.DocTestFinder().find(f)[0]
837
838 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000839 Trying:
840 x = 12
841 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000842 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000843 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000844 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000845 Expecting:
846 12
Tim Peters8485b562004-08-04 18:46:34 +0000847 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000848 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000849 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000850 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000851 6
Tim Peters8485b562004-08-04 18:46:34 +0000852 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000853 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000854
855If the `verbose` flag is unspecified, then the output will be verbose
856iff `-v` appears in sys.argv:
857
858 >>> # Save the real sys.argv list.
859 >>> old_argv = sys.argv
860
861 >>> # If -v does not appear in sys.argv, then output isn't verbose.
862 >>> sys.argv = ['test']
863 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000864 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000865
866 >>> # If -v does appear in sys.argv, then output is verbose.
867 >>> sys.argv = ['test', '-v']
868 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000869 Trying:
870 x = 12
871 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000872 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000873 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000874 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000875 Expecting:
876 12
Tim Peters8485b562004-08-04 18:46:34 +0000877 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000878 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000879 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000880 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000881 6
Tim Peters8485b562004-08-04 18:46:34 +0000882 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000883 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000884
885 >>> # Restore sys.argv
886 >>> sys.argv = old_argv
887
888In the remaining examples, the test runner's verbosity will be
889explicitly set, to ensure that the test behavior is consistent.
890 """
891 def exceptions(): r"""
892Tests of `DocTestRunner`'s exception handling.
893
894An expected exception is specified with a traceback message. The
895lines between the first line and the type/value may be omitted or
896replaced with any other string:
897
898 >>> def f(x):
899 ... '''
900 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000901 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000902 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000903 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000904 ... '''
905 >>> test = doctest.DocTestFinder().find(f)[0]
906 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000907 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000908
Edward Loper19b19582004-08-25 23:07:03 +0000909An example may not generate output before it raises an exception; if
910it does, then the traceback message will not be recognized as
911signaling an expected exception, so the example will be reported as an
912unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000913
914 >>> def f(x):
915 ... '''
916 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000917 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000918 ... pre-exception output
919 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000920 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000921 ... '''
922 >>> test = doctest.DocTestFinder().find(f)[0]
923 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000924 ... # doctest: +ELLIPSIS
925 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000926 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000927 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000928 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000929 Exception raised:
930 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000931 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000932 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000933
934Exception messages may contain newlines:
935
936 >>> def f(x):
937 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000938 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000939 ... Traceback (most recent call last):
940 ... ValueError: multi
941 ... line
942 ... message
943 ... '''
944 >>> test = doctest.DocTestFinder().find(f)[0]
945 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000946 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000947
948If an exception is expected, but an exception with the wrong type or
949message is raised, then it is reported as a failure:
950
951 >>> def f(x):
952 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000953 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000954 ... Traceback (most recent call last):
955 ... ValueError: wrong message
956 ... '''
957 >>> test = doctest.DocTestFinder().find(f)[0]
958 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000959 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000960 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000961 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000962 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000963 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000964 Expected:
965 Traceback (most recent call last):
966 ValueError: wrong message
967 Got:
968 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000969 ...
Tim Peters8485b562004-08-04 18:46:34 +0000970 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000971 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000972
Tim Peters1fbf9c52004-09-04 17:21:02 +0000973However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
974detail:
975
976 >>> def f(x):
977 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000978 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000979 ... Traceback (most recent call last):
980 ... ValueError: wrong message
981 ... '''
982 >>> test = doctest.DocTestFinder().find(f)[0]
983 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000984 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000985
Nick Coghlan5e76e942010-06-12 13:42:46 +0000986IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
987between Python versions. For example, in Python 2.x, the module path of
988the exception is not in the output, but this will fail under Python 3:
989
990 >>> def f(x):
991 ... r'''
992 ... >>> from http.client import HTTPException
993 ... >>> raise HTTPException('message')
994 ... Traceback (most recent call last):
995 ... HTTPException: message
996 ... '''
997 >>> test = doctest.DocTestFinder().find(f)[0]
998 >>> doctest.DocTestRunner(verbose=False).run(test)
999 ... # doctest: +ELLIPSIS
1000 **********************************************************************
1001 File ..., line 4, in f
1002 Failed example:
1003 raise HTTPException('message')
1004 Expected:
1005 Traceback (most recent call last):
1006 HTTPException: message
1007 Got:
1008 Traceback (most recent call last):
1009 ...
1010 http.client.HTTPException: message
1011 TestResults(failed=1, attempted=2)
1012
1013But in Python 3 the module path is included, and therefore a test must look
1014like the following test to succeed in Python 3. But that test will fail under
1015Python 2.
1016
1017 >>> def f(x):
1018 ... r'''
1019 ... >>> from http.client import HTTPException
1020 ... >>> raise HTTPException('message')
1021 ... Traceback (most recent call last):
1022 ... http.client.HTTPException: message
1023 ... '''
1024 >>> test = doctest.DocTestFinder().find(f)[0]
1025 >>> doctest.DocTestRunner(verbose=False).run(test)
1026 TestResults(failed=0, attempted=2)
1027
1028However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1029(or its unexpected absence) will be ignored:
1030
1031 >>> def f(x):
1032 ... r'''
1033 ... >>> from http.client import HTTPException
1034 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1035 ... Traceback (most recent call last):
1036 ... HTTPException: message
1037 ... '''
1038 >>> test = doctest.DocTestFinder().find(f)[0]
1039 >>> doctest.DocTestRunner(verbose=False).run(test)
1040 TestResults(failed=0, attempted=2)
1041
1042The module path will be completely ignored, so two different module paths will
1043still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1044be used when exceptions have changed module.
1045
1046 >>> def f(x):
1047 ... r'''
1048 ... >>> from http.client import HTTPException
1049 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1050 ... Traceback (most recent call last):
1051 ... foo.bar.HTTPException: message
1052 ... '''
1053 >>> test = doctest.DocTestFinder().find(f)[0]
1054 >>> doctest.DocTestRunner(verbose=False).run(test)
1055 TestResults(failed=0, attempted=2)
1056
Tim Peters1fbf9c52004-09-04 17:21:02 +00001057But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1058
1059 >>> def f(x):
1060 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001061 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001062 ... Traceback (most recent call last):
1063 ... TypeError: wrong type
1064 ... '''
1065 >>> test = doctest.DocTestFinder().find(f)[0]
1066 >>> doctest.DocTestRunner(verbose=False).run(test)
1067 ... # doctest: +ELLIPSIS
1068 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001069 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001070 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001071 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001072 Expected:
1073 Traceback (most recent call last):
1074 TypeError: wrong type
1075 Got:
1076 Traceback (most recent call last):
1077 ...
1078 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001079 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001080
Tim Petersf9a07f22013-12-03 21:02:05 -06001081If the exception does not have a message, you can still use
1082IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1083
1084 >>> def f(x):
1085 ... r'''
1086 ... >>> from http.client import HTTPException
1087 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1088 ... Traceback (most recent call last):
1089 ... foo.bar.HTTPException
1090 ... '''
1091 >>> test = doctest.DocTestFinder().find(f)[0]
1092 >>> doctest.DocTestRunner(verbose=False).run(test)
1093 TestResults(failed=0, attempted=2)
1094
1095Note that a trailing colon doesn't matter either:
1096
1097 >>> def f(x):
1098 ... r'''
1099 ... >>> from http.client import HTTPException
1100 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1101 ... Traceback (most recent call last):
1102 ... foo.bar.HTTPException:
1103 ... '''
1104 >>> test = doctest.DocTestFinder().find(f)[0]
1105 >>> doctest.DocTestRunner(verbose=False).run(test)
1106 TestResults(failed=0, attempted=2)
1107
Tim Peters8485b562004-08-04 18:46:34 +00001108If an exception is raised but not expected, then it is reported as an
1109unexpected exception:
1110
Tim Peters8485b562004-08-04 18:46:34 +00001111 >>> def f(x):
1112 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001113 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001114 ... 0
1115 ... '''
1116 >>> test = doctest.DocTestFinder().find(f)[0]
1117 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001118 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001119 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001120 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001121 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001122 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001123 Exception raised:
1124 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001125 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001126 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001127 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001128"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001129 def displayhook(): r"""
1130Test that changing sys.displayhook doesn't matter for doctest.
1131
1132 >>> import sys
1133 >>> orig_displayhook = sys.displayhook
1134 >>> def my_displayhook(x):
1135 ... print('hi!')
1136 >>> sys.displayhook = my_displayhook
1137 >>> def f():
1138 ... '''
1139 ... >>> 3
1140 ... 3
1141 ... '''
1142 >>> test = doctest.DocTestFinder().find(f)[0]
1143 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1144 >>> post_displayhook = sys.displayhook
1145
1146 We need to restore sys.displayhook now, so that we'll be able to test
1147 results.
1148
1149 >>> sys.displayhook = orig_displayhook
1150
1151 Ok, now we can check that everything is ok.
1152
1153 >>> r
1154 TestResults(failed=0, attempted=1)
1155 >>> post_displayhook is my_displayhook
1156 True
1157"""
Tim Peters8485b562004-08-04 18:46:34 +00001158 def optionflags(): r"""
1159Tests of `DocTestRunner`'s option flag handling.
1160
1161Several option flags can be used to customize the behavior of the test
1162runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001163to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001164together).
1165
1166The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1167and 1/0:
1168
1169 >>> def f(x):
1170 ... '>>> True\n1\n'
1171
1172 >>> # Without the flag:
1173 >>> test = doctest.DocTestFinder().find(f)[0]
1174 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001175 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001176
1177 >>> # With the flag:
1178 >>> test = doctest.DocTestFinder().find(f)[0]
1179 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1180 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001181 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001182 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001183 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001184 Failed example:
1185 True
1186 Expected:
1187 1
1188 Got:
1189 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001190 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001191
1192The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1193and the '<BLANKLINE>' marker:
1194
1195 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001196 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001197
1198 >>> # Without the flag:
1199 >>> test = doctest.DocTestFinder().find(f)[0]
1200 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001201 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001202
1203 >>> # With the flag:
1204 >>> test = doctest.DocTestFinder().find(f)[0]
1205 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1206 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001207 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001208 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001209 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001210 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001211 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001212 Expected:
1213 a
1214 <BLANKLINE>
1215 b
1216 Got:
1217 a
1218 <BLANKLINE>
1219 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001220 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001221
1222The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1223treated as equal:
1224
1225 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001226 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001227
1228 >>> # Without the flag:
1229 >>> test = doctest.DocTestFinder().find(f)[0]
1230 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001231 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001232 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001233 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001234 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001235 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001236 Expected:
1237 1 2
1238 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001239 Got:
1240 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001241 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001242
1243 >>> # With the flag:
1244 >>> test = doctest.DocTestFinder().find(f)[0]
1245 >>> flags = doctest.NORMALIZE_WHITESPACE
1246 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001247 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001248
Tim Peters026f8dc2004-08-19 16:38:58 +00001249 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001250 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001251 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1252 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1253
Tim Peters8485b562004-08-04 18:46:34 +00001254The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1255output to match any substring in the actual output:
1256
1257 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001258 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001259
1260 >>> # Without the flag:
1261 >>> test = doctest.DocTestFinder().find(f)[0]
1262 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001263 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001264 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001265 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001266 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001267 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001268 Expected:
1269 [0, 1, 2, ..., 14]
1270 Got:
1271 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001272 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001273
1274 >>> # With the flag:
1275 >>> test = doctest.DocTestFinder().find(f)[0]
1276 >>> flags = doctest.ELLIPSIS
1277 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001278 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001279
Tim Peterse594bee2004-08-22 01:47:51 +00001280 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001281
Guido van Rossume0192e52007-02-09 23:39:59 +00001282 >>> if 1:
1283 ... for i in range(100):
1284 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1285 ... print('!')
1286 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001287
Tim Peters026f8dc2004-08-19 16:38:58 +00001288 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001289
Guido van Rossume0192e52007-02-09 23:39:59 +00001290 >>> if 1: #doctest: +ELLIPSIS
1291 ... for i in range(20):
1292 ... print(i, end=' ')
1293 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001294 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001295
Tim Peters026f8dc2004-08-19 16:38:58 +00001296 Examples from the docs:
1297
Guido van Rossum805365e2007-05-07 22:24:25 +00001298 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001299 [0, 1, ..., 18, 19]
1300
Guido van Rossum805365e2007-05-07 22:24:25 +00001301 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001302 ... # doctest: +NORMALIZE_WHITESPACE
1303 [0, 1, ..., 18, 19]
1304
Thomas Wouters477c8d52006-05-27 19:21:47 +00001305The SKIP flag causes an example to be skipped entirely. I.e., the
1306example is not run. It can be useful in contexts where doctest
1307examples serve as both documentation and test cases, and an example
1308should be included for documentation purposes, but should not be
1309checked (e.g., because its output is random, or depends on resources
1310which would be unavailable.) The SKIP flag can also be used for
1311'commenting out' broken examples.
1312
1313 >>> import unavailable_resource # doctest: +SKIP
1314 >>> unavailable_resource.do_something() # doctest: +SKIP
1315 >>> unavailable_resource.blow_up() # doctest: +SKIP
1316 Traceback (most recent call last):
1317 ...
1318 UncheckedBlowUpError: Nobody checks me.
1319
1320 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001321 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001322 0.721216923889
1323
Edward Loper71f55af2004-08-26 01:41:51 +00001324The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001325and actual outputs to be displayed using a unified diff:
1326
1327 >>> def f(x):
1328 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001329 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001330 ... a
1331 ... B
1332 ... c
1333 ... d
1334 ... f
1335 ... g
1336 ... h
1337 ... '''
1338
1339 >>> # Without the flag:
1340 >>> test = doctest.DocTestFinder().find(f)[0]
1341 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001342 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001343 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001344 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001345 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001346 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001347 Expected:
1348 a
1349 B
1350 c
1351 d
1352 f
1353 g
1354 h
1355 Got:
1356 a
1357 b
1358 c
1359 d
1360 e
1361 f
1362 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001363 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001364
1365 >>> # With the flag:
1366 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001367 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001368 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001369 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001370 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001371 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001372 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001373 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001374 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001375 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001376 a
1377 -B
1378 +b
1379 c
1380 d
1381 +e
1382 f
1383 g
1384 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001385 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001386
Edward Loper71f55af2004-08-26 01:41:51 +00001387The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001388and actual outputs to be displayed using a context diff:
1389
Edward Loper71f55af2004-08-26 01:41:51 +00001390 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001391 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001392 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001393 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001394 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001395 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001396 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001397 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001398 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001399 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001400 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001401 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001402 a
1403 ! B
1404 c
1405 d
1406 f
1407 g
1408 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001409 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001410 a
1411 ! b
1412 c
1413 d
1414 + e
1415 f
1416 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001417 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001418
1419
Edward Loper71f55af2004-08-26 01:41:51 +00001420The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001421used by the popular ndiff.py utility. This does intraline difference
1422marking, as well as interline differences.
1423
1424 >>> def f(x):
1425 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001426 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001427 ... a b c d e f g h i j k 1 m
1428 ... '''
1429 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001430 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001431 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001432 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001433 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001434 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001435 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001436 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001437 Differences (ndiff with -expected +actual):
1438 - a b c d e f g h i j k 1 m
1439 ? ^
1440 + a b c d e f g h i j k l m
1441 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001442 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001443
Ezio Melotti13925002011-03-16 11:05:33 +02001444The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001445failing example:
1446
1447 >>> def f(x):
1448 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001449 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001450 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001451 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001452 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001453 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001454 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001455 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001456 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001457 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001458 ... 500
1459 ... '''
1460 >>> test = doctest.DocTestFinder().find(f)[0]
1461 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1462 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001463 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001464 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001465 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001466 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001467 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001468 Expected:
1469 200
1470 Got:
1471 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001472 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001473
Ezio Melotti13925002011-03-16 11:05:33 +02001474However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001475
1476 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001477 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001478 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001479 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001480 Expecting:
1481 1
1482 ok
1483 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001484 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001485 Expecting:
1486 200
1487 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001488 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001489 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001490 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001491 Expected:
1492 200
1493 Got:
1494 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001495 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001496
R David Murray5a9d7062012-11-21 15:09:21 -05001497The FAIL_FAST flag causes the runner to exit after the first failing example,
1498so subsequent examples are not even attempted:
1499
1500 >>> flags = doctest.FAIL_FAST
1501 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1502 ... # doctest: +ELLIPSIS
1503 **********************************************************************
1504 File ..., line 5, in f
1505 Failed example:
1506 print(2) # first failure
1507 Expected:
1508 200
1509 Got:
1510 2
1511 TestResults(failed=1, attempted=2)
1512
1513Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1514FAIL_FAST only:
1515
1516 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1517 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1518 ... # doctest: +ELLIPSIS
1519 **********************************************************************
1520 File ..., line 5, in f
1521 Failed example:
1522 print(2) # first failure
1523 Expected:
1524 200
1525 Got:
1526 2
1527 TestResults(failed=1, attempted=2)
1528
1529For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1530exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001531
1532 >>> def f(x):
1533 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001534 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001535 ... 1
1536 ... >>> raise ValueError(2) # first failure
1537 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001538 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001539 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001540 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001541 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001542 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001543 ... 500
1544 ... '''
1545 >>> test = doctest.DocTestFinder().find(f)[0]
1546 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1547 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1548 ... # doctest: +ELLIPSIS
1549 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001550 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001551 Failed example:
1552 raise ValueError(2) # first failure
1553 Exception raised:
1554 ...
1555 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001556 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001557 >>> flags = doctest.FAIL_FAST
1558 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1559 ... # doctest: +ELLIPSIS
1560 **********************************************************************
1561 File ..., line 5, in f
1562 Failed example:
1563 raise ValueError(2) # first failure
1564 Exception raised:
1565 ...
1566 ValueError: 2
1567 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001568
Thomas Wouters477c8d52006-05-27 19:21:47 +00001569New option flags can also be registered, via register_optionflag(). Here
1570we reach into doctest's internals a bit.
1571
1572 >>> unlikely = "UNLIKELY_OPTION_NAME"
1573 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1574 False
1575 >>> new_flag_value = doctest.register_optionflag(unlikely)
1576 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1577 True
1578
1579Before 2.4.4/2.5, registering a name more than once erroneously created
1580more than one flag value. Here we verify that's fixed:
1581
1582 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1583 >>> redundant_flag_value == new_flag_value
1584 True
1585
1586Clean up.
1587 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1588
Tim Petersc6cbab02004-08-22 19:43:28 +00001589 """
1590
Tim Peters8485b562004-08-04 18:46:34 +00001591 def option_directives(): r"""
1592Tests of `DocTestRunner`'s option directive mechanism.
1593
Edward Loper74bca7a2004-08-12 02:27:44 +00001594Option directives can be used to turn option flags on or off for a
1595single example. To turn an option on for an example, follow that
1596example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001597
1598 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001599 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001600 ... [0, 1, ..., 9]
1601 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001602 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001603 ... [0, 1, ..., 9]
1604 ... '''
1605 >>> test = doctest.DocTestFinder().find(f)[0]
1606 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001607 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001608 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001609 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001610 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001611 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001612 Expected:
1613 [0, 1, ..., 9]
1614 Got:
1615 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001616 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001617
1618To turn an option off for an example, follow that example with a
1619comment of the form ``# doctest: -OPTION``:
1620
1621 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001622 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001623 ... [0, 1, ..., 9]
1624 ...
1625 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001626 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001627 ... [0, 1, ..., 9]
1628 ... '''
1629 >>> test = doctest.DocTestFinder().find(f)[0]
1630 >>> doctest.DocTestRunner(verbose=False,
1631 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001632 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001633 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001634 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001635 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001636 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001637 Expected:
1638 [0, 1, ..., 9]
1639 Got:
1640 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001641 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001642
1643Option directives affect only the example that they appear with; they
1644do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001645
Edward Loper74bca7a2004-08-12 02:27:44 +00001646 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001647 ... >>> print(list(range(10))) # Should fail: no 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))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001651 ... [0, 1, ..., 9]
1652 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001653 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001654 ... [0, 1, ..., 9]
1655 ... '''
1656 >>> test = doctest.DocTestFinder().find(f)[0]
1657 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001658 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001659 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001660 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001661 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001662 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001663 Expected:
1664 [0, 1, ..., 9]
1665 Got:
1666 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001667 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001668 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001669 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001670 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001671 Expected:
1672 [0, 1, ..., 9]
1673 Got:
1674 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001675 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001676
Edward Loper74bca7a2004-08-12 02:27:44 +00001677Multiple options may be modified by a single option directive. They
1678may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001679
1680 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001681 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001682 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001683 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001684 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001685 ... [0, 1, ..., 9]
1686 ... '''
1687 >>> test = doctest.DocTestFinder().find(f)[0]
1688 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001689 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001690 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001691 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001692 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001693 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001694 Expected:
1695 [0, 1, ..., 9]
1696 Got:
1697 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001698 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001699
1700 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001701 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001702 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001703 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001704 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1705 ... [0, 1, ..., 9]
1706 ... '''
1707 >>> test = doctest.DocTestFinder().find(f)[0]
1708 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001709 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001710 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001711 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001712 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001713 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001714 Expected:
1715 [0, 1, ..., 9]
1716 Got:
1717 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001718 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001719
1720 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001721 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001722 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001723 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001724 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1725 ... [0, 1, ..., 9]
1726 ... '''
1727 >>> test = doctest.DocTestFinder().find(f)[0]
1728 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001729 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001730 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001731 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001732 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001733 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001734 Expected:
1735 [0, 1, ..., 9]
1736 Got:
1737 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001738 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001739
1740The option directive may be put on the line following the source, as
1741long as a continuation prompt is used:
1742
1743 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001744 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001745 ... ... # doctest: +ELLIPSIS
1746 ... [0, 1, ..., 9]
1747 ... '''
1748 >>> test = doctest.DocTestFinder().find(f)[0]
1749 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001750 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001751
Edward Loper74bca7a2004-08-12 02:27:44 +00001752For examples with multi-line source, the option directive may appear
1753at the end of any line:
1754
1755 >>> def f(x): r'''
1756 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001757 ... ... print(' ', x, end='', sep='')
1758 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001759 ...
1760 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001761 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1762 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001763 ... '''
1764 >>> test = doctest.DocTestFinder().find(f)[0]
1765 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001766 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001767
1768If more than one line of an example with multi-line source has an
1769option directive, then they are combined:
1770
1771 >>> def f(x): r'''
1772 ... Should fail (option directive not on the last line):
1773 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001774 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001775 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001776 ... '''
1777 >>> test = doctest.DocTestFinder().find(f)[0]
1778 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001779 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001780
1781It is an error to have a comment of the form ``# doctest:`` that is
1782*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1783``OPTION`` is an option that has been registered with
1784`register_option`:
1785
1786 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001787 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001788 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1789 Traceback (most recent call last):
1790 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1791
1792 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001793 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001794 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1795 Traceback (most recent call last):
1796 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1797
1798It is an error to use an option directive on a line that contains no
1799source:
1800
1801 >>> s = '>>> # doctest: +ELLIPSIS'
1802 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1803 Traceback (most recent call last):
1804 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 +00001805"""
1806
1807def test_testsource(): r"""
1808Unit tests for `testsource()`.
1809
1810The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001811test with that name in that module, and converts it to a script. The
1812example code is converted to regular Python code. The surrounding
1813words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001814
1815 >>> import test.test_doctest
1816 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001817 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001818 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001819 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001820 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001821 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001822 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001823 #
Edward Lopera5db6002004-08-12 02:41:30 +00001824 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001825 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001826
1827 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001828 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001829 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001830 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001831 ## 1
1832 ## 2
1833 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001834 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001835
1836 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001837 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001838 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001839 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001840 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001841 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001842 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001843 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001844 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001845"""
1846
1847def test_debug(): r"""
1848
1849Create a docstring that we want to debug:
1850
1851 >>> s = '''
1852 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001853 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001854 ... 12
1855 ... '''
1856
1857Create some fake stdin input, to feed to the debugger:
1858
Tim Peters8485b562004-08-04 18:46:34 +00001859 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001860 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001861
1862Run the debugger on the docstring, and then restore sys.stdin.
1863
Edward Loper2de91ba2004-08-27 02:07:46 +00001864 >>> try: doctest.debug_src(s)
1865 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001866 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001867 (Pdb) next
1868 12
Tim Peters8485b562004-08-04 18:46:34 +00001869 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001871 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001872 12
1873 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001874
1875"""
1876
Brett Cannon31f59292011-02-21 19:29:56 +00001877if not hasattr(sys, 'gettrace') or not sys.gettrace():
1878 def test_pdb_set_trace():
1879 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001880
Brett Cannon31f59292011-02-21 19:29:56 +00001881 You can use pdb.set_trace from a doctest. To do so, you must
1882 retrieve the set_trace function from the pdb module at the time
1883 you use it. The doctest module changes sys.stdout so that it can
1884 capture program output. It also temporarily replaces pdb.set_trace
1885 with a version that restores stdout. This is necessary for you to
1886 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001887
Brett Cannon31f59292011-02-21 19:29:56 +00001888 >>> doc = '''
1889 ... >>> x = 42
1890 ... >>> raise Exception('clé')
1891 ... Traceback (most recent call last):
1892 ... Exception: clé
1893 ... >>> import pdb; pdb.set_trace()
1894 ... '''
1895 >>> parser = doctest.DocTestParser()
1896 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1897 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001898
Brett Cannon31f59292011-02-21 19:29:56 +00001899 To demonstrate this, we'll create a fake standard input that
1900 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001901
Brett Cannon31f59292011-02-21 19:29:56 +00001902 >>> real_stdin = sys.stdin
1903 >>> sys.stdin = _FakeInput([
1904 ... 'print(x)', # print data defined by the example
1905 ... 'continue', # stop debugging
1906 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001907
Brett Cannon31f59292011-02-21 19:29:56 +00001908 >>> try: runner.run(test)
1909 ... finally: sys.stdin = real_stdin
1910 --Return--
1911 > <doctest foo-bar@baz[2]>(1)<module>()->None
1912 -> import pdb; pdb.set_trace()
1913 (Pdb) print(x)
1914 42
1915 (Pdb) continue
1916 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001917
Brett Cannon31f59292011-02-21 19:29:56 +00001918 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001919
Brett Cannon31f59292011-02-21 19:29:56 +00001920 >>> def calls_set_trace():
1921 ... y=2
1922 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001923
Brett Cannon31f59292011-02-21 19:29:56 +00001924 >>> doc = '''
1925 ... >>> x=1
1926 ... >>> calls_set_trace()
1927 ... '''
1928 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1929 >>> real_stdin = sys.stdin
1930 >>> sys.stdin = _FakeInput([
1931 ... 'print(y)', # print data defined in the function
1932 ... 'up', # out of function
1933 ... 'print(x)', # print data defined by the example
1934 ... 'continue', # stop debugging
1935 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001936
Brett Cannon31f59292011-02-21 19:29:56 +00001937 >>> try:
1938 ... runner.run(test)
1939 ... finally:
1940 ... sys.stdin = real_stdin
1941 --Return--
Serhiy Storchakae437a102016-04-24 21:41:02 +03001942 > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
Brett Cannon31f59292011-02-21 19:29:56 +00001943 -> import pdb; pdb.set_trace()
1944 (Pdb) print(y)
1945 2
1946 (Pdb) up
1947 > <doctest foo-bar@baz[1]>(1)<module>()
1948 -> calls_set_trace()
1949 (Pdb) print(x)
1950 1
1951 (Pdb) continue
1952 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001953
Brett Cannon31f59292011-02-21 19:29:56 +00001954 During interactive debugging, source code is shown, even for
1955 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001956
Brett Cannon31f59292011-02-21 19:29:56 +00001957 >>> doc = '''
1958 ... >>> def f(x):
1959 ... ... g(x*2)
1960 ... >>> def g(x):
1961 ... ... print(x+3)
1962 ... ... import pdb; pdb.set_trace()
1963 ... >>> f(3)
1964 ... '''
1965 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1966 >>> real_stdin = sys.stdin
1967 >>> sys.stdin = _FakeInput([
1968 ... 'list', # list source from example 2
1969 ... 'next', # return from g()
1970 ... 'list', # list source from example 1
1971 ... 'next', # return from f()
1972 ... 'list', # list source from example 3
1973 ... 'continue', # stop debugging
1974 ... ''])
1975 >>> try: runner.run(test)
1976 ... finally: sys.stdin = real_stdin
1977 ... # doctest: +NORMALIZE_WHITESPACE
1978 --Return--
1979 > <doctest foo-bar@baz[1]>(3)g()->None
1980 -> import pdb; pdb.set_trace()
1981 (Pdb) list
1982 1 def g(x):
1983 2 print(x+3)
1984 3 -> import pdb; pdb.set_trace()
1985 [EOF]
1986 (Pdb) next
1987 --Return--
1988 > <doctest foo-bar@baz[0]>(2)f()->None
1989 -> g(x*2)
1990 (Pdb) list
1991 1 def f(x):
1992 2 -> g(x*2)
1993 [EOF]
1994 (Pdb) next
1995 --Return--
1996 > <doctest foo-bar@baz[2]>(1)<module>()->None
1997 -> f(3)
1998 (Pdb) list
1999 1 -> f(3)
2000 [EOF]
2001 (Pdb) continue
2002 **********************************************************************
2003 File "foo-bar@baz.py", line 7, in foo-bar@baz
2004 Failed example:
2005 f(3)
2006 Expected nothing
2007 Got:
2008 9
2009 TestResults(failed=1, attempted=3)
2010 """
Jim Fulton356fd192004-08-09 11:34:47 +00002011
Brett Cannon31f59292011-02-21 19:29:56 +00002012 def test_pdb_set_trace_nested():
2013 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00002014
Brett Cannon31f59292011-02-21 19:29:56 +00002015 >>> class C(object):
2016 ... def calls_set_trace(self):
2017 ... y = 1
2018 ... import pdb; pdb.set_trace()
2019 ... self.f1()
2020 ... y = 2
2021 ... def f1(self):
2022 ... x = 1
2023 ... self.f2()
2024 ... x = 2
2025 ... def f2(self):
2026 ... z = 1
2027 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002028
Brett Cannon31f59292011-02-21 19:29:56 +00002029 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002030
Brett Cannon31f59292011-02-21 19:29:56 +00002031 >>> doc = '''
2032 ... >>> a = 1
2033 ... >>> calls_set_trace()
2034 ... '''
2035 >>> parser = doctest.DocTestParser()
2036 >>> runner = doctest.DocTestRunner(verbose=False)
2037 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2038 >>> real_stdin = sys.stdin
2039 >>> sys.stdin = _FakeInput([
2040 ... 'print(y)', # print data defined in the function
2041 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2042 ... 'up', 'print(x)',
2043 ... 'up', 'print(y)',
2044 ... 'up', 'print(foo)',
2045 ... 'continue', # stop debugging
2046 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002047
Brett Cannon31f59292011-02-21 19:29:56 +00002048 >>> try:
2049 ... runner.run(test)
2050 ... finally:
2051 ... sys.stdin = real_stdin
2052 ... # doctest: +REPORT_NDIFF
2053 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2054 -> self.f1()
2055 (Pdb) print(y)
2056 1
2057 (Pdb) step
2058 --Call--
2059 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2060 -> def f1(self):
2061 (Pdb) step
2062 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2063 -> x = 1
2064 (Pdb) step
2065 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2066 -> self.f2()
2067 (Pdb) step
2068 --Call--
2069 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2070 -> def f2(self):
2071 (Pdb) step
2072 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2073 -> z = 1
2074 (Pdb) step
2075 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2076 -> z = 2
2077 (Pdb) print(z)
2078 1
2079 (Pdb) up
2080 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2081 -> self.f2()
2082 (Pdb) print(x)
2083 1
2084 (Pdb) up
2085 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2086 -> self.f1()
2087 (Pdb) print(y)
2088 1
2089 (Pdb) up
2090 > <doctest foo-bar@baz[1]>(1)<module>()
2091 -> calls_set_trace()
2092 (Pdb) print(foo)
2093 *** NameError: name 'foo' is not defined
2094 (Pdb) continue
2095 TestResults(failed=0, attempted=2)
2096 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002097
Tim Peters19397e52004-08-06 22:02:59 +00002098def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002099 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002100
2101 We create a Suite by providing a module. A module can be provided
2102 by passing a module object:
2103
2104 >>> import unittest
2105 >>> import test.sample_doctest
2106 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2107 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002108 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002109
2110 We can also supply the module by name:
2111
2112 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2113 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002114 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002115
R David Murray5abd76a2012-09-10 10:15:58 -04002116 The module need not contain any doctest examples:
2117
2118 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2119 >>> suite.run(unittest.TestResult())
2120 <unittest.result.TestResult run=0 errors=0 failures=0>
2121
R David Murray1976d9b2014-04-14 20:28:36 -04002122 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002123
R David Murray1976d9b2014-04-14 20:28:36 -04002124 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002125 >>> suite.run(unittest.TestResult())
2126 <unittest.result.TestResult run=0 errors=0 failures=0>
2127
Tim Peters19397e52004-08-06 22:02:59 +00002128 We can use the current module:
2129
2130 >>> suite = test.sample_doctest.test_suite()
2131 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002132 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002133
R David Murray1976d9b2014-04-14 20:28:36 -04002134 We can also provide a DocTestFinder:
2135
2136 >>> finder = doctest.DocTestFinder()
2137 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2138 ... test_finder=finder)
2139 >>> suite.run(unittest.TestResult())
2140 <unittest.result.TestResult run=9 errors=0 failures=4>
2141
2142 The DocTestFinder need not return any tests:
2143
2144 >>> finder = doctest.DocTestFinder()
2145 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2146 ... test_finder=finder)
2147 >>> suite.run(unittest.TestResult())
2148 <unittest.result.TestResult run=0 errors=0 failures=0>
2149
Tim Peters19397e52004-08-06 22:02:59 +00002150 We can supply global variables. If we pass globs, they will be
2151 used instead of the module globals. Here we'll pass an empty
2152 globals, triggering an extra error:
2153
2154 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2155 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002156 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002157
2158 Alternatively, we can provide extra globals. Here we'll make an
2159 error go away by providing an extra global variable:
2160
2161 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2162 ... extraglobs={'y': 1})
2163 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002164 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002165
2166 You can pass option flags. Here we'll cause an extra error
2167 by disabling the blank-line feature:
2168
2169 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002170 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002171 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002172 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002173
Tim Peters1e277ee2004-08-07 05:37:52 +00002174 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002175
Jim Fultonf54bad42004-08-28 14:57:56 +00002176 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002177 ... import test.test_doctest
2178 ... test.test_doctest.sillySetup = True
2179
Jim Fultonf54bad42004-08-28 14:57:56 +00002180 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002181 ... import test.test_doctest
2182 ... del test.test_doctest.sillySetup
2183
2184 Here, we installed a silly variable that the test expects:
2185
2186 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2187 ... setUp=setUp, tearDown=tearDown)
2188 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002189 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002190
2191 But the tearDown restores sanity:
2192
2193 >>> import test.test_doctest
2194 >>> test.test_doctest.sillySetup
2195 Traceback (most recent call last):
2196 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002197 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002198
Berker Peksag4882cac2015-04-14 09:30:01 +03002199 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002200 we'll use the setUp function to supply the missing variable y:
2201
2202 >>> def setUp(test):
2203 ... test.globs['y'] = 1
2204
2205 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2206 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002207 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002208
2209 Here, we didn't need to use a tearDown function because we
2210 modified the test globals, which are a copy of the
2211 sample_doctest module dictionary. The test globals are
2212 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002213 """
2214
2215def test_DocFileSuite():
2216 """We can test tests found in text files using a DocFileSuite.
2217
2218 We create a suite by providing the names of one or more text
2219 files that include examples:
2220
2221 >>> import unittest
2222 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002223 ... 'test_doctest2.txt',
2224 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002225 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002226 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002227
2228 The test files are looked for in the directory containing the
2229 calling module. A package keyword argument can be provided to
2230 specify a different relative location.
2231
2232 >>> import unittest
2233 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2234 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002235 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002236 ... package='test')
2237 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002238 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002239
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002240 Support for using a package's __loader__.get_data() is also
2241 provided.
2242
2243 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002244 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002245 >>> if not hasattr(test, '__loader__'):
2246 ... test.__loader__ = pkgutil.get_loader(test)
2247 ... added_loader = True
2248 >>> try:
2249 ... suite = doctest.DocFileSuite('test_doctest.txt',
2250 ... 'test_doctest2.txt',
2251 ... 'test_doctest4.txt',
2252 ... package='test')
2253 ... suite.run(unittest.TestResult())
2254 ... finally:
2255 ... if added_loader:
2256 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002257 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002258
Edward Loper0273f5b2004-09-18 20:27:04 +00002259 '/' should be used as a path separator. It will be converted
2260 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002261
2262 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2263 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002264 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002265
Edward Loper0273f5b2004-09-18 20:27:04 +00002266 If DocFileSuite is used from an interactive session, then files
2267 are resolved relative to the directory of sys.argv[0]:
2268
Christian Heimes45f9af32007-11-27 21:50:00 +00002269 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002270 >>> save_argv = sys.argv
2271 >>> sys.argv = [test.test_doctest.__file__]
2272 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002273 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002274 >>> sys.argv = save_argv
2275
Edward Loper052d0cd2004-09-19 17:19:33 +00002276 By setting `module_relative=False`, os-specific paths may be
2277 used (including absolute paths and paths relative to the
2278 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002279
2280 >>> # Get the absolute path of the test package.
2281 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2282 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2283
2284 >>> # Use it to find the absolute path of test_doctest.txt.
2285 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2286
Edward Loper052d0cd2004-09-19 17:19:33 +00002287 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002288 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002289 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002290
Edward Loper052d0cd2004-09-19 17:19:33 +00002291 It is an error to specify `package` when `module_relative=False`:
2292
2293 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2294 ... package='test')
2295 Traceback (most recent call last):
2296 ValueError: Package may only be specified for module-relative paths.
2297
Tim Peters19397e52004-08-06 22:02:59 +00002298 You can specify initial global variables:
2299
2300 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2301 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002302 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002303 ... globs={'favorite_color': 'blue'})
2304 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002305 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002306
2307 In this case, we supplied a missing favorite color. You can
2308 provide doctest options:
2309
2310 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2311 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002312 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002313 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2314 ... globs={'favorite_color': 'blue'})
2315 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002316 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002317
2318 And, you can provide setUp and tearDown functions:
2319
Jim Fultonf54bad42004-08-28 14:57:56 +00002320 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002321 ... import test.test_doctest
2322 ... test.test_doctest.sillySetup = True
2323
Jim Fultonf54bad42004-08-28 14:57:56 +00002324 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002325 ... import test.test_doctest
2326 ... del test.test_doctest.sillySetup
2327
2328 Here, we installed a silly variable that the test expects:
2329
2330 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2331 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002332 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002333 ... setUp=setUp, tearDown=tearDown)
2334 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002335 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002336
2337 But the tearDown restores sanity:
2338
2339 >>> import test.test_doctest
2340 >>> test.test_doctest.sillySetup
2341 Traceback (most recent call last):
2342 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002343 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002344
Berker Peksag4882cac2015-04-14 09:30:01 +03002345 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002346 Here, we'll use a setUp function to set the favorite color in
2347 test_doctest.txt:
2348
2349 >>> def setUp(test):
2350 ... test.globs['favorite_color'] = 'blue'
2351
2352 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2353 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002354 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002355
2356 Here, we didn't need to use a tearDown function because we
2357 modified the test globals. The test globals are
2358 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002359
Fred Drake7c404a42004-12-21 23:46:34 +00002360 Tests in a file run using `DocFileSuite` can also access the
2361 `__file__` global, which is set to the name of the file
2362 containing the tests:
2363
Benjamin Petersonab078e92016-07-13 21:13:29 -07002364 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
Fred Drake7c404a42004-12-21 23:46:34 +00002365 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002366 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002367
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002368 If the tests contain non-ASCII characters, we have to specify which
2369 encoding the file is encoded with. We do so by using the `encoding`
2370 parameter:
2371
2372 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2373 ... 'test_doctest2.txt',
2374 ... 'test_doctest4.txt',
2375 ... encoding='utf-8')
2376 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002377 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002378
Jim Fultonf54bad42004-08-28 14:57:56 +00002379 """
Tim Peters19397e52004-08-06 22:02:59 +00002380
Jim Fulton07a349c2004-08-22 14:10:00 +00002381def test_trailing_space_in_test():
2382 """
Tim Petersa7def722004-08-23 22:13:22 +00002383 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002384
Jim Fulton07a349c2004-08-22 14:10:00 +00002385 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002386 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002387 foo \n
2388 """
Tim Peters19397e52004-08-06 22:02:59 +00002389
Yury Selivanovb532df62014-12-08 15:00:05 -05002390class Wrapper:
2391 def __init__(self, func):
2392 self.func = func
2393 functools.update_wrapper(self, func)
2394
2395 def __call__(self, *args, **kwargs):
2396 self.func(*args, **kwargs)
2397
2398@Wrapper
2399def test_look_in_unwrapped():
2400 """
2401 Docstrings in wrapped functions must be detected as well.
2402
2403 >>> 'one other test'
2404 'one other test'
2405 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002406
2407def test_unittest_reportflags():
2408 """Default unittest reporting flags can be set to control reporting
2409
2410 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2411 only the first failure of each test. First, we'll look at the
2412 output without the flag. The file test_doctest.txt file has two
2413 tests. They both fail if blank lines are disabled:
2414
2415 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2416 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2417 >>> import unittest
2418 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002419 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002420 Traceback ...
2421 Failed example:
2422 favorite_color
2423 ...
2424 Failed example:
2425 if 1:
2426 ...
2427
2428 Note that we see both failures displayed.
2429
2430 >>> old = doctest.set_unittest_reportflags(
2431 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2432
2433 Now, when we run the test:
2434
2435 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002436 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002437 Traceback ...
2438 Failed example:
2439 favorite_color
2440 Exception raised:
2441 ...
2442 NameError: name 'favorite_color' is not defined
2443 <BLANKLINE>
2444 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002445
Jim Fultonf54bad42004-08-28 14:57:56 +00002446 We get only the first failure.
2447
2448 If we give any reporting options when we set up the tests,
2449 however:
2450
2451 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2452 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2453
2454 Then the default eporting options are ignored:
2455
2456 >>> result = suite.run(unittest.TestResult())
Pablo Galindoc5dc60e2019-01-10 14:29:40 +00002457
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302458 *NOTE*: These doctest are intentionally not placed in raw string to depict
2459 the trailing whitespace using `\x20` in the diff below.
2460
Guido van Rossum7131f842007-02-09 20:13:25 +00002461 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002462 Traceback ...
2463 Failed example:
2464 favorite_color
2465 ...
2466 Failed example:
2467 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002468 print('a')
2469 print()
2470 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002471 Differences (ndiff with -expected +actual):
2472 a
2473 - <BLANKLINE>
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302474 +\x20
Jim Fultonf54bad42004-08-28 14:57:56 +00002475 b
2476 <BLANKLINE>
2477 <BLANKLINE>
2478
2479
2480 Test runners can restore the formatting flags after they run:
2481
2482 >>> ignored = doctest.set_unittest_reportflags(old)
2483
2484 """
2485
Edward Loper052d0cd2004-09-19 17:19:33 +00002486def test_testfile(): r"""
2487Tests for the `testfile()` function. This function runs all the
2488doctest examples in a given file. In its simple invokation, it is
2489called with the name of a file, which is taken to be relative to the
2490calling module. The return value is (#failures, #tests).
2491
Florent Xicluna59250852010-02-27 14:21:57 +00002492We don't want `-v` in sys.argv for these tests.
2493
2494 >>> save_argv = sys.argv
2495 >>> if '-v' in sys.argv:
2496 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2497
2498
Edward Loper052d0cd2004-09-19 17:19:33 +00002499 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2500 **********************************************************************
2501 File "...", line 6, in test_doctest.txt
2502 Failed example:
2503 favorite_color
2504 Exception raised:
2505 ...
2506 NameError: name 'favorite_color' is not defined
2507 **********************************************************************
2508 1 items had failures:
2509 1 of 2 in test_doctest.txt
2510 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002511 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002512 >>> doctest.master = None # Reset master.
2513
2514(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002515`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002516same name.)
2517
2518Globals may be specified with the `globs` and `extraglobs` parameters:
2519
2520 >>> globs = {'favorite_color': 'blue'}
2521 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002522 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002523 >>> doctest.master = None # Reset master.
2524
2525 >>> extraglobs = {'favorite_color': 'red'}
2526 >>> doctest.testfile('test_doctest.txt', globs=globs,
2527 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2528 **********************************************************************
2529 File "...", line 6, in test_doctest.txt
2530 Failed example:
2531 favorite_color
2532 Expected:
2533 'blue'
2534 Got:
2535 'red'
2536 **********************************************************************
2537 1 items had failures:
2538 1 of 2 in test_doctest.txt
2539 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002540 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002541 >>> doctest.master = None # Reset master.
2542
2543The file may be made relative to a given module or package, using the
2544optional `module_relative` parameter:
2545
2546 >>> doctest.testfile('test_doctest.txt', globs=globs,
2547 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002548 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002549 >>> doctest.master = None # Reset master.
2550
Ezio Melotti13925002011-03-16 11:05:33 +02002551Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002552
2553 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2554 Trying:
2555 favorite_color
2556 Expecting:
2557 'blue'
2558 ok
2559 Trying:
2560 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002561 print('a')
2562 print()
2563 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002564 Expecting:
2565 a
2566 <BLANKLINE>
2567 b
2568 ok
2569 1 items passed all tests:
2570 2 tests in test_doctest.txt
2571 2 tests in 1 items.
2572 2 passed and 0 failed.
2573 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002574 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002575 >>> doctest.master = None # Reset master.
2576
2577The name of the test may be specified with the optional `name`
2578parameter:
2579
2580 >>> doctest.testfile('test_doctest.txt', name='newname')
2581 ... # doctest: +ELLIPSIS
2582 **********************************************************************
2583 File "...", line 6, in newname
2584 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002585 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002586 >>> doctest.master = None # Reset master.
2587
Ezio Melotti13925002011-03-16 11:05:33 +02002588The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002589parameter:
2590
2591 >>> doctest.testfile('test_doctest.txt', report=False)
2592 ... # doctest: +ELLIPSIS
2593 **********************************************************************
2594 File "...", line 6, in test_doctest.txt
2595 Failed example:
2596 favorite_color
2597 Exception raised:
2598 ...
2599 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002600 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002601 >>> doctest.master = None # Reset master.
2602
2603The optional keyword argument `raise_on_error` can be used to raise an
2604exception on the first error (which may be useful for postmortem
2605debugging):
2606
2607 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2608 ... # doctest: +ELLIPSIS
2609 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002610 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002611 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002612
2613If the tests contain non-ASCII characters, the tests might fail, since
2614it's unknown which encoding is used. The encoding can be specified
2615using the optional keyword argument `encoding`:
2616
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002617 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002618 **********************************************************************
2619 File "...", line 7, in test_doctest4.txt
2620 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002621 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002622 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002623 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002624 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002625 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002626 **********************************************************************
2627 ...
2628 **********************************************************************
2629 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002630 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002631 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002632 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002633 >>> doctest.master = None # Reset master.
2634
2635 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002636 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002637 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002638
2639Test the verbose output:
2640
2641 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2642 Trying:
2643 'föö'
2644 Expecting:
2645 'f\xf6\xf6'
2646 ok
2647 Trying:
2648 'bÄ…r'
2649 Expecting:
2650 'b\u0105r'
2651 ok
2652 1 items passed all tests:
2653 2 tests in test_doctest4.txt
2654 2 tests in 1 items.
2655 2 passed and 0 failed.
2656 Test passed.
2657 TestResults(failed=0, attempted=2)
2658 >>> doctest.master = None # Reset master.
2659 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002660"""
2661
R David Murrayb48cb292014-10-02 22:42:42 -04002662def test_lineendings(): r"""
2663*nix systems use \n line endings, while Windows systems use \r\n. Python
2664handles this using universal newline mode for reading files. Let's make
2665sure doctest does so (issue 8473) by creating temporary test files using each
2666of the two line disciplines. One of the two will be the "wrong" one for the
2667platform the test is run on.
2668
2669Windows line endings first:
2670
2671 >>> import tempfile, os
2672 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002673 >>> with open(fn, 'wb') as f:
2674 ... 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 -04002675 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002676 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002677 TestResults(failed=0, attempted=1)
2678 >>> os.remove(fn)
2679
2680And now *nix line endings:
2681
2682 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002683 >>> with open(fn, 'wb') as f:
2684 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002685 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002686 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002687 TestResults(failed=0, attempted=1)
2688 >>> os.remove(fn)
2689
2690"""
2691
R. David Murray58641de2009-06-12 15:33:19 +00002692def test_testmod(): r"""
2693Tests for the testmod function. More might be useful, but for now we're just
2694testing the case raised by Issue 6195, where trying to doctest a C module would
2695fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2696out of the binary module.
2697
2698 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002699 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002700 TestResults(failed=0, attempted=0)
2701"""
2702
Victor Stinner9d396392010-10-16 21:54:59 +00002703try:
2704 os.fsencode("foo-bär@baz.py")
2705except UnicodeEncodeError:
2706 # Skip the test: the filesystem encoding is unable to encode the filename
2707 pass
2708else:
2709 def test_unicode(): """
2710Check doctest with a non-ascii filename:
2711
2712 >>> doc = '''
2713 ... >>> raise Exception('clé')
2714 ... '''
2715 ...
2716 >>> parser = doctest.DocTestParser()
2717 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2718 >>> test
2719 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2720 >>> runner = doctest.DocTestRunner(verbose=False)
2721 >>> runner.run(test) # doctest: +ELLIPSIS
2722 **********************************************************************
2723 File "foo-bär@baz.py", line 2, in foo-bär@baz
2724 Failed example:
2725 raise Exception('clé')
2726 Exception raised:
2727 Traceback (most recent call last):
2728 File ...
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03002729 exec(compile(example.source, filename, "single",
Victor Stinner9d396392010-10-16 21:54:59 +00002730 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2731 raise Exception('clé')
2732 Exception: clé
2733 TestResults(failed=1, attempted=1)
2734 """
2735
R David Murray5707d502013-06-23 14:24:13 -04002736def test_CLI(): r"""
2737The doctest module can be used to run doctests against an arbitrary file.
2738These tests test this CLI functionality.
2739
2740We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002741to a temp dir to run the command against. Due to a current limitation in
2742script_helpers, though, we need a little utility function to turn the returned
2743output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002744
R David Murray4af68982013-06-25 08:11:22 -04002745 >>> def normalize(s):
2746 ... return '\n'.join(s.decode().splitlines())
2747
R David Murray4af68982013-06-25 08:11:22 -04002748With those preliminaries out of the way, we'll start with a file with two
2749simple tests and no errors. We'll run both the unadorned doctest command, and
2750the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002751
Berker Peksagce643912015-05-06 06:33:17 +03002752 >>> from test.support import script_helper, temp_dir
2753 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002754 ... fn = os.path.join(tmpdir, 'myfile.doc')
2755 ... with open(fn, 'w') as f:
2756 ... _ = f.write('This is a very simple test file.\n')
2757 ... _ = f.write(' >>> 1 + 1\n')
2758 ... _ = f.write(' 2\n')
2759 ... _ = f.write(' >>> "a"\n')
2760 ... _ = f.write(" 'a'\n")
2761 ... _ = f.write('\n')
2762 ... _ = f.write('And that is it.\n')
2763 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002764 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002765 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002766 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002767
2768With no arguments and passing tests, we should get no output:
2769
2770 >>> rc1, out1, err1
2771 (0, b'', b'')
2772
2773With the verbose flag, we should see the test output, but no error output:
2774
2775 >>> rc2, err2
2776 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002777 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002778 Trying:
2779 1 + 1
2780 Expecting:
2781 2
2782 ok
2783 Trying:
2784 "a"
2785 Expecting:
2786 'a'
2787 ok
2788 1 items passed all tests:
2789 2 tests in myfile.doc
2790 2 tests in 1 items.
2791 2 passed and 0 failed.
2792 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002793
2794Now we'll write a couple files, one with three tests, the other a python module
2795with two tests, both of the files having "errors" in the tests that can be made
2796non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2797the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002798allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002799ability to process more than one file on the command line and, since the second
2800file ends in '.py', its handling of python module files (as opposed to straight
2801text files).
2802
Berker Peksagce643912015-05-06 06:33:17 +03002803 >>> from test.support import script_helper, temp_dir
2804 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002805 ... fn = os.path.join(tmpdir, 'myfile.doc')
2806 ... with open(fn, 'w') as f:
2807 ... _ = f.write('This is another simple test file.\n')
2808 ... _ = f.write(' >>> 1 + 1\n')
2809 ... _ = f.write(' 2\n')
2810 ... _ = f.write(' >>> "abcdef"\n')
2811 ... _ = f.write(" 'a...f'\n")
2812 ... _ = f.write(' >>> "ajkml"\n')
2813 ... _ = f.write(" 'a...l'\n")
2814 ... _ = f.write('\n')
2815 ... _ = f.write('And that is it.\n')
2816 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2817 ... with open(fn2, 'w') as f:
2818 ... _ = f.write('def test_func():\n')
2819 ... _ = f.write(' \"\"\"\n')
2820 ... _ = f.write(' This is simple python test function.\n')
2821 ... _ = f.write(' >>> 1 + 1\n')
2822 ... _ = f.write(' 2\n')
2823 ... _ = f.write(' >>> "abc def"\n')
2824 ... _ = f.write(" 'abc def'\n")
2825 ... _ = f.write("\n")
2826 ... _ = f.write(' \"\"\"\n')
R David Murray5707d502013-06-23 14:24:13 -04002827 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002828 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002829 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002830 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002831 ... rc3, out3, err3 = script_helper.assert_python_ok(
2832 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002833 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002834 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002835 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002836 ... rc5, out5, err5 = script_helper.assert_python_ok(
2837 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002838 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002839
2840Our first test run will show the errors from the first file (doctest stops if a
2841file has errors). Note that doctest test-run error output appears on stdout,
2842not stderr:
2843
2844 >>> rc1, err1
2845 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002846 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002847 **********************************************************************
2848 File "...myfile.doc", line 4, in myfile.doc
2849 Failed example:
2850 "abcdef"
2851 Expected:
2852 'a...f'
2853 Got:
2854 'abcdef'
2855 **********************************************************************
2856 File "...myfile.doc", line 6, in myfile.doc
2857 Failed example:
2858 "ajkml"
2859 Expected:
2860 'a...l'
2861 Got:
2862 'ajkml'
2863 **********************************************************************
2864 1 items had failures:
2865 2 of 3 in myfile.doc
2866 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002867
2868With -o ELLIPSIS specified, the second run, against just the first file, should
2869produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2870should the third, which ran against both files:
2871
2872 >>> rc2, out2, err2
2873 (0, b'', b'')
2874 >>> rc3, out3, err3
2875 (0, b'', b'')
2876
2877The fourth run uses FAIL_FAST, so we should see only one error:
2878
2879 >>> rc4, err4
2880 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002881 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002882 **********************************************************************
2883 File "...myfile.doc", line 4, in myfile.doc
2884 Failed example:
2885 "abcdef"
2886 Expected:
2887 'a...f'
2888 Got:
2889 'abcdef'
2890 **********************************************************************
2891 1 items had failures:
2892 1 of 2 in myfile.doc
2893 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002894
2895The fifth test uses verbose with the two options, so we should get verbose
2896success output for the tests in both files:
2897
2898 >>> rc5, err5
2899 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002900 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002901 Trying:
2902 1 + 1
2903 Expecting:
2904 2
2905 ok
2906 Trying:
2907 "abcdef"
2908 Expecting:
2909 'a...f'
2910 ok
2911 Trying:
2912 "ajkml"
2913 Expecting:
2914 'a...l'
2915 ok
2916 1 items passed all tests:
2917 3 tests in myfile.doc
2918 3 tests in 1 items.
2919 3 passed and 0 failed.
2920 Test passed.
2921 Trying:
2922 1 + 1
2923 Expecting:
2924 2
2925 ok
2926 Trying:
2927 "abc def"
2928 Expecting:
2929 'abc def'
2930 ok
2931 1 items had no tests:
2932 myfile2
2933 1 items passed all tests:
2934 2 tests in myfile2.test_func
2935 2 tests in 2 items.
2936 2 passed and 0 failed.
2937 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002938
2939We should also check some typical error cases.
2940
2941Invalid file name:
2942
2943 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002944 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04002945 >>> rc, out
2946 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002947 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002948 Traceback (most recent call last):
2949 ...
2950 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
2951
2952Invalid doctest option:
2953
2954 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002955 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04002956 >>> rc, out
2957 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04002958 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002959 usage...invalid...nosuchoption...
2960
2961"""
2962
Sanyam Khuranacbb16452019-01-09 19:08:38 +05302963def test_no_trailing_whitespace_stripping():
2964 r"""
2965 The fancy reports had a bug for a long time where any trailing whitespace on
2966 the reported diff lines was stripped, making it impossible to see the
2967 differences in line reported as different that differed only in the amount of
2968 trailing whitespace. The whitespace still isn't particularly visible unless
2969 you use NDIFF, but at least it is now there to be found.
2970
2971 *NOTE*: This snippet was intentionally put inside a raw string to get rid of
2972 leading whitespace error in executing the example below
2973
2974 >>> def f(x):
2975 ... r'''
2976 ... >>> print('\n'.join(['a ', 'b']))
2977 ... a
2978 ... b
2979 ... '''
2980 """
2981 """
2982 *NOTE*: These doctest are not placed in raw string to depict the trailing whitespace
2983 using `\x20`
2984
2985 >>> test = doctest.DocTestFinder().find(f)[0]
2986 >>> flags = doctest.REPORT_NDIFF
2987 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
2988 ... # doctest: +ELLIPSIS
2989 **********************************************************************
2990 File ..., line 3, in f
2991 Failed example:
2992 print('\n'.join(['a ', 'b']))
2993 Differences (ndiff with -expected +actual):
2994 - a
2995 + a
2996 b
2997 TestResults(failed=1, attempted=1)
2998
2999 *NOTE*: `\x20` is for checking the trailing whitespace on the +a line above.
3000 We cannot use actual spaces there, as a commit hook prevents from committing
3001 patches that contain trailing whitespace. More info on Issue 24746.
3002 """
3003
Tim Peters8485b562004-08-04 18:46:34 +00003004######################################################################
3005## Main
3006######################################################################
3007
3008def test_main():
3009 # Check the doctest cases in doctest itself:
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02003010 ret = support.run_doctest(doctest, verbosity=True)
Victor Stinner931602a2016-03-25 12:48:17 +01003011
Tim Peters8485b562004-08-04 18:46:34 +00003012 # Check the doctest cases defined here:
3013 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003014 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00003015
Jason R. Coombsb9650a02018-03-05 18:29:08 -05003016 # Run unittests
3017 support.run_unittest(__name__)
3018
3019
Tim Peters8485b562004-08-04 18:46:34 +00003020def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00003021 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01003022 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00003023 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00003024 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00003025 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003026 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00003027 r.write_results(show_missing=True, summary=True,
3028 coverdir=coverdir)
3029
3030if __name__ == '__main__':
3031 if '-c' in sys.argv:
3032 test_coverage('/tmp/doctest.cover')
3033 else:
3034 test_main()