blob: 83941c129f44630e1b73df8ed5c3439d1f745252 [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
Miss Islington (bot)5a0c3982018-03-06 07:16:11 -080010import importlib
11import unittest
Nick Coghlanee378452018-03-25 23:43:50 +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
Miss Islington (bot)5a0c3982018-03-06 07:16:11 -0800440 [<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
Zachary Warea4b7a752013-11-24 01:19:09 -0600668 8
669 >>> for t in real_tests:
670 ... print('{} {}'.format(len(t.examples), t.name))
671 ...
672 1 builtins.bin
673 3 builtins.float.as_integer_ratio
674 2 builtins.float.fromhex
675 2 builtins.float.hex
676 1 builtins.hex
677 1 builtins.int
678 2 builtins.int.bit_length
679 1 builtins.oct
680
681Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
682'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
683and 'int' is a type.
Tim Peters8485b562004-08-04 18:46:34 +0000684"""
685
Miss Islington (bot)5a0c3982018-03-06 07:16:11 -0800686
687class TestDocTestFinder(unittest.TestCase):
688
689 def test_empty_namespace_package(self):
690 pkg_name = 'doctest_empty_pkg'
Nick Coghlanee378452018-03-25 23:43:50 +1000691 with tempfile.TemporaryDirectory() as parent_dir:
692 pkg_dir = os.path.join(parent_dir, pkg_name)
693 os.mkdir(pkg_dir)
694 sys.path.append(parent_dir)
695 try:
696 mod = importlib.import_module(pkg_name)
697 finally:
698 support.forget(pkg_name)
699 sys.path.pop()
700 assert doctest.DocTestFinder().find(mod) == []
Miss Islington (bot)5a0c3982018-03-06 07:16:11 -0800701
702
Edward Loper00f8da72004-08-26 18:05:07 +0000703def test_DocTestParser(): r"""
704Unit tests for the `DocTestParser` class.
705
706DocTestParser is used to parse docstrings containing doctest examples.
707
708The `parse` method divides a docstring into examples and intervening
709text:
710
711 >>> s = '''
712 ... >>> x, y = 2, 3 # no output expected
713 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000714 ... ... print(x)
715 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000716 ... 2
717 ... 3
718 ...
719 ... Some text.
720 ... >>> x+y
721 ... 5
722 ... '''
723 >>> parser = doctest.DocTestParser()
724 >>> for piece in parser.parse(s):
725 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000726 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000727 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000728 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000729 Text: '\n'
730 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
731 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000732 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000733 Text: '\nSome text.\n'
734 Example: ('x+y\n', '5\n', 9)
735 Text: ''
736
737The `get_examples` method returns just the examples:
738
739 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000740 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000741 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000742 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000743 ('x+y\n', '5\n', 9)
744
745The `get_doctest` method creates a Test from the examples, along with the
746given arguments:
747
748 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
749 >>> (test.name, test.filename, test.lineno)
750 ('name', 'filename', 5)
751 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000752 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000753 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000754 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000755 ('x+y\n', '5\n', 9)
756"""
757
Tim Peters8485b562004-08-04 18:46:34 +0000758class test_DocTestRunner:
759 def basics(): r"""
760Unit tests for the `DocTestRunner` class.
761
762DocTestRunner is used to run DocTest test cases, and to accumulate
763statistics. Here's a simple DocTest case we can use:
764
765 >>> def f(x):
766 ... '''
767 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000768 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000769 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000770 ... >>> x//2
771 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000772 ... '''
773 >>> test = doctest.DocTestFinder().find(f)[0]
774
775The main DocTestRunner interface is the `run` method, which runs a
776given DocTest case in a given namespace (globs). It returns a tuple
777`(f,t)`, where `f` is the number of failed tests and `t` is the number
778of tried tests.
779
780 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000781 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000782
783If any example produces incorrect output, then the test runner reports
784the failure and proceeds to the next example:
785
786 >>> def f(x):
787 ... '''
788 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000789 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000790 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000791 ... >>> x//2
792 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000793 ... '''
794 >>> test = doctest.DocTestFinder().find(f)[0]
795 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000796 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000797 Trying:
798 x = 12
799 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000800 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000801 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000802 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000803 Expecting:
804 14
Tim Peters8485b562004-08-04 18:46:34 +0000805 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000806 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000807 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000808 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000809 Expected:
810 14
811 Got:
812 12
Edward Loperaacf0832004-08-26 01:19:50 +0000813 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000814 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000815 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000816 6
Tim Peters8485b562004-08-04 18:46:34 +0000817 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000818 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000819"""
820 def verbose_flag(): r"""
821The `verbose` flag makes the test runner generate more detailed
822output:
823
824 >>> def f(x):
825 ... '''
826 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000827 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000828 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000829 ... >>> x//2
830 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000831 ... '''
832 >>> test = doctest.DocTestFinder().find(f)[0]
833
834 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000835 Trying:
836 x = 12
837 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000838 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000839 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000840 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000841 Expecting:
842 12
Tim Peters8485b562004-08-04 18:46:34 +0000843 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000844 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000846 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000847 6
Tim Peters8485b562004-08-04 18:46:34 +0000848 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000849 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000850
851If the `verbose` flag is unspecified, then the output will be verbose
852iff `-v` appears in sys.argv:
853
854 >>> # Save the real sys.argv list.
855 >>> old_argv = sys.argv
856
857 >>> # If -v does not appear in sys.argv, then output isn't verbose.
858 >>> sys.argv = ['test']
859 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000860 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000861
862 >>> # If -v does appear in sys.argv, then output is verbose.
863 >>> sys.argv = ['test', '-v']
864 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000865 Trying:
866 x = 12
867 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000868 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000869 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000870 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000871 Expecting:
872 12
Tim Peters8485b562004-08-04 18:46:34 +0000873 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000874 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000875 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000876 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000877 6
Tim Peters8485b562004-08-04 18:46:34 +0000878 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000879 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000880
881 >>> # Restore sys.argv
882 >>> sys.argv = old_argv
883
884In the remaining examples, the test runner's verbosity will be
885explicitly set, to ensure that the test behavior is consistent.
886 """
887 def exceptions(): r"""
888Tests of `DocTestRunner`'s exception handling.
889
890An expected exception is specified with a traceback message. The
891lines between the first line and the type/value may be omitted or
892replaced with any other string:
893
894 >>> def f(x):
895 ... '''
896 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000897 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000898 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000899 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000900 ... '''
901 >>> test = doctest.DocTestFinder().find(f)[0]
902 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000903 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000904
Edward Loper19b19582004-08-25 23:07:03 +0000905An example may not generate output before it raises an exception; if
906it does, then the traceback message will not be recognized as
907signaling an expected exception, so the example will be reported as an
908unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000909
910 >>> def f(x):
911 ... '''
912 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000913 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000914 ... pre-exception output
915 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000916 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000917 ... '''
918 >>> test = doctest.DocTestFinder().find(f)[0]
919 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000920 ... # doctest: +ELLIPSIS
921 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000922 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000923 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000924 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000925 Exception raised:
926 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000927 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000928 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000929
930Exception messages may contain newlines:
931
932 >>> def f(x):
933 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000934 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000935 ... Traceback (most recent call last):
936 ... ValueError: multi
937 ... line
938 ... message
939 ... '''
940 >>> test = doctest.DocTestFinder().find(f)[0]
941 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000942 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000943
944If an exception is expected, but an exception with the wrong type or
945message is raised, then it is reported as a failure:
946
947 >>> def f(x):
948 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000949 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000950 ... Traceback (most recent call last):
951 ... ValueError: wrong message
952 ... '''
953 >>> test = doctest.DocTestFinder().find(f)[0]
954 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000955 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000956 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000957 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000958 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000959 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000960 Expected:
961 Traceback (most recent call last):
962 ValueError: wrong message
963 Got:
964 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000965 ...
Tim Peters8485b562004-08-04 18:46:34 +0000966 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000967 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000968
Tim Peters1fbf9c52004-09-04 17:21:02 +0000969However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
970detail:
971
972 >>> def f(x):
973 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000974 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000975 ... Traceback (most recent call last):
976 ... ValueError: wrong message
977 ... '''
978 >>> test = doctest.DocTestFinder().find(f)[0]
979 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000980 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000981
Nick Coghlan5e76e942010-06-12 13:42:46 +0000982IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
983between Python versions. For example, in Python 2.x, the module path of
984the exception is not in the output, but this will fail under Python 3:
985
986 >>> def f(x):
987 ... r'''
988 ... >>> from http.client import HTTPException
989 ... >>> raise HTTPException('message')
990 ... Traceback (most recent call last):
991 ... HTTPException: message
992 ... '''
993 >>> test = doctest.DocTestFinder().find(f)[0]
994 >>> doctest.DocTestRunner(verbose=False).run(test)
995 ... # doctest: +ELLIPSIS
996 **********************************************************************
997 File ..., line 4, in f
998 Failed example:
999 raise HTTPException('message')
1000 Expected:
1001 Traceback (most recent call last):
1002 HTTPException: message
1003 Got:
1004 Traceback (most recent call last):
1005 ...
1006 http.client.HTTPException: message
1007 TestResults(failed=1, attempted=2)
1008
1009But in Python 3 the module path is included, and therefore a test must look
1010like the following test to succeed in Python 3. But that test will fail under
1011Python 2.
1012
1013 >>> def f(x):
1014 ... r'''
1015 ... >>> from http.client import HTTPException
1016 ... >>> raise HTTPException('message')
1017 ... Traceback (most recent call last):
1018 ... http.client.HTTPException: message
1019 ... '''
1020 >>> test = doctest.DocTestFinder().find(f)[0]
1021 >>> doctest.DocTestRunner(verbose=False).run(test)
1022 TestResults(failed=0, attempted=2)
1023
1024However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1025(or its unexpected absence) will be ignored:
1026
1027 >>> def f(x):
1028 ... r'''
1029 ... >>> from http.client import HTTPException
1030 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1031 ... Traceback (most recent call last):
1032 ... HTTPException: message
1033 ... '''
1034 >>> test = doctest.DocTestFinder().find(f)[0]
1035 >>> doctest.DocTestRunner(verbose=False).run(test)
1036 TestResults(failed=0, attempted=2)
1037
1038The module path will be completely ignored, so two different module paths will
1039still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1040be used when exceptions have changed module.
1041
1042 >>> def f(x):
1043 ... r'''
1044 ... >>> from http.client import HTTPException
1045 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1046 ... Traceback (most recent call last):
1047 ... foo.bar.HTTPException: message
1048 ... '''
1049 >>> test = doctest.DocTestFinder().find(f)[0]
1050 >>> doctest.DocTestRunner(verbose=False).run(test)
1051 TestResults(failed=0, attempted=2)
1052
Tim Peters1fbf9c52004-09-04 17:21:02 +00001053But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1054
1055 >>> def f(x):
1056 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001057 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001058 ... Traceback (most recent call last):
1059 ... TypeError: wrong type
1060 ... '''
1061 >>> test = doctest.DocTestFinder().find(f)[0]
1062 >>> doctest.DocTestRunner(verbose=False).run(test)
1063 ... # doctest: +ELLIPSIS
1064 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001065 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001066 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001067 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001068 Expected:
1069 Traceback (most recent call last):
1070 TypeError: wrong type
1071 Got:
1072 Traceback (most recent call last):
1073 ...
1074 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001075 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001076
Tim Petersf9a07f22013-12-03 21:02:05 -06001077If the exception does not have a message, you can still use
1078IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1079
1080 >>> def f(x):
1081 ... r'''
1082 ... >>> from http.client import HTTPException
1083 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1084 ... Traceback (most recent call last):
1085 ... foo.bar.HTTPException
1086 ... '''
1087 >>> test = doctest.DocTestFinder().find(f)[0]
1088 >>> doctest.DocTestRunner(verbose=False).run(test)
1089 TestResults(failed=0, attempted=2)
1090
1091Note that a trailing colon doesn't matter either:
1092
1093 >>> def f(x):
1094 ... r'''
1095 ... >>> from http.client import HTTPException
1096 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1097 ... Traceback (most recent call last):
1098 ... foo.bar.HTTPException:
1099 ... '''
1100 >>> test = doctest.DocTestFinder().find(f)[0]
1101 >>> doctest.DocTestRunner(verbose=False).run(test)
1102 TestResults(failed=0, attempted=2)
1103
Tim Peters8485b562004-08-04 18:46:34 +00001104If an exception is raised but not expected, then it is reported as an
1105unexpected exception:
1106
Tim Peters8485b562004-08-04 18:46:34 +00001107 >>> def f(x):
1108 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001109 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001110 ... 0
1111 ... '''
1112 >>> test = doctest.DocTestFinder().find(f)[0]
1113 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001114 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001115 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001116 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001117 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001118 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001119 Exception raised:
1120 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001121 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001122 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001123 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001124"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001125 def displayhook(): r"""
1126Test that changing sys.displayhook doesn't matter for doctest.
1127
1128 >>> import sys
1129 >>> orig_displayhook = sys.displayhook
1130 >>> def my_displayhook(x):
1131 ... print('hi!')
1132 >>> sys.displayhook = my_displayhook
1133 >>> def f():
1134 ... '''
1135 ... >>> 3
1136 ... 3
1137 ... '''
1138 >>> test = doctest.DocTestFinder().find(f)[0]
1139 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1140 >>> post_displayhook = sys.displayhook
1141
1142 We need to restore sys.displayhook now, so that we'll be able to test
1143 results.
1144
1145 >>> sys.displayhook = orig_displayhook
1146
1147 Ok, now we can check that everything is ok.
1148
1149 >>> r
1150 TestResults(failed=0, attempted=1)
1151 >>> post_displayhook is my_displayhook
1152 True
1153"""
Tim Peters8485b562004-08-04 18:46:34 +00001154 def optionflags(): r"""
1155Tests of `DocTestRunner`'s option flag handling.
1156
1157Several option flags can be used to customize the behavior of the test
1158runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001159to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001160together).
1161
1162The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1163and 1/0:
1164
1165 >>> def f(x):
1166 ... '>>> True\n1\n'
1167
1168 >>> # Without the flag:
1169 >>> test = doctest.DocTestFinder().find(f)[0]
1170 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001171 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001172
1173 >>> # With the flag:
1174 >>> test = doctest.DocTestFinder().find(f)[0]
1175 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1176 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001177 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001178 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001179 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001180 Failed example:
1181 True
1182 Expected:
1183 1
1184 Got:
1185 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001186 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001187
1188The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1189and the '<BLANKLINE>' marker:
1190
1191 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001192 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001193
1194 >>> # Without the flag:
1195 >>> test = doctest.DocTestFinder().find(f)[0]
1196 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001197 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001198
1199 >>> # With the flag:
1200 >>> test = doctest.DocTestFinder().find(f)[0]
1201 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1202 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001203 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001204 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001205 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001206 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001207 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001208 Expected:
1209 a
1210 <BLANKLINE>
1211 b
1212 Got:
1213 a
1214 <BLANKLINE>
1215 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001216 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001217
1218The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1219treated as equal:
1220
1221 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001222 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001223
1224 >>> # Without the flag:
1225 >>> test = doctest.DocTestFinder().find(f)[0]
1226 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001227 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001228 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001229 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001230 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001231 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001232 Expected:
1233 1 2
1234 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001235 Got:
1236 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001237 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001238
1239 >>> # With the flag:
1240 >>> test = doctest.DocTestFinder().find(f)[0]
1241 >>> flags = doctest.NORMALIZE_WHITESPACE
1242 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001243 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001244
Tim Peters026f8dc2004-08-19 16:38:58 +00001245 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001246 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001247 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1248 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1249
Tim Peters8485b562004-08-04 18:46:34 +00001250The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1251output to match any substring in the actual output:
1252
1253 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001254 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001255
1256 >>> # Without the flag:
1257 >>> test = doctest.DocTestFinder().find(f)[0]
1258 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001259 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001260 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001261 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001262 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001263 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001264 Expected:
1265 [0, 1, 2, ..., 14]
1266 Got:
1267 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001268 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001269
1270 >>> # With the flag:
1271 >>> test = doctest.DocTestFinder().find(f)[0]
1272 >>> flags = doctest.ELLIPSIS
1273 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001274 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001275
Tim Peterse594bee2004-08-22 01:47:51 +00001276 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001277
Guido van Rossume0192e52007-02-09 23:39:59 +00001278 >>> if 1:
1279 ... for i in range(100):
1280 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1281 ... print('!')
1282 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001283
Tim Peters026f8dc2004-08-19 16:38:58 +00001284 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001285
Guido van Rossume0192e52007-02-09 23:39:59 +00001286 >>> if 1: #doctest: +ELLIPSIS
1287 ... for i in range(20):
1288 ... print(i, end=' ')
1289 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001290 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001291
Tim Peters026f8dc2004-08-19 16:38:58 +00001292 Examples from the docs:
1293
Guido van Rossum805365e2007-05-07 22:24:25 +00001294 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001295 [0, 1, ..., 18, 19]
1296
Guido van Rossum805365e2007-05-07 22:24:25 +00001297 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001298 ... # doctest: +NORMALIZE_WHITESPACE
1299 [0, 1, ..., 18, 19]
1300
Thomas Wouters477c8d52006-05-27 19:21:47 +00001301The SKIP flag causes an example to be skipped entirely. I.e., the
1302example is not run. It can be useful in contexts where doctest
1303examples serve as both documentation and test cases, and an example
1304should be included for documentation purposes, but should not be
1305checked (e.g., because its output is random, or depends on resources
1306which would be unavailable.) The SKIP flag can also be used for
1307'commenting out' broken examples.
1308
1309 >>> import unavailable_resource # doctest: +SKIP
1310 >>> unavailable_resource.do_something() # doctest: +SKIP
1311 >>> unavailable_resource.blow_up() # doctest: +SKIP
1312 Traceback (most recent call last):
1313 ...
1314 UncheckedBlowUpError: Nobody checks me.
1315
1316 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001317 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001318 0.721216923889
1319
Edward Loper71f55af2004-08-26 01:41:51 +00001320The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001321and actual outputs to be displayed using a unified diff:
1322
1323 >>> def f(x):
1324 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001325 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001326 ... a
1327 ... B
1328 ... c
1329 ... d
1330 ... f
1331 ... g
1332 ... h
1333 ... '''
1334
1335 >>> # Without the flag:
1336 >>> test = doctest.DocTestFinder().find(f)[0]
1337 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001338 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001339 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001340 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001341 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001342 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001343 Expected:
1344 a
1345 B
1346 c
1347 d
1348 f
1349 g
1350 h
1351 Got:
1352 a
1353 b
1354 c
1355 d
1356 e
1357 f
1358 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001359 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001360
1361 >>> # With the flag:
1362 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001363 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001364 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001365 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001366 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001367 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001368 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001369 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001370 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001371 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001372 a
1373 -B
1374 +b
1375 c
1376 d
1377 +e
1378 f
1379 g
1380 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001381 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001382
Edward Loper71f55af2004-08-26 01:41:51 +00001383The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001384and actual outputs to be displayed using a context diff:
1385
Edward Loper71f55af2004-08-26 01:41:51 +00001386 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001387 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001388 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001389 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001390 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001391 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001392 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001393 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001394 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001395 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001396 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001397 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001398 a
1399 ! B
1400 c
1401 d
1402 f
1403 g
1404 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001405 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001406 a
1407 ! b
1408 c
1409 d
1410 + e
1411 f
1412 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001413 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001414
1415
Edward Loper71f55af2004-08-26 01:41:51 +00001416The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001417used by the popular ndiff.py utility. This does intraline difference
1418marking, as well as interline differences.
1419
1420 >>> def f(x):
1421 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001422 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001423 ... a b c d e f g h i j k 1 m
1424 ... '''
1425 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001426 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001427 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001428 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001429 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001430 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001431 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001432 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001433 Differences (ndiff with -expected +actual):
1434 - a b c d e f g h i j k 1 m
1435 ? ^
1436 + a b c d e f g h i j k l m
1437 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001438 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001439
Ezio Melotti13925002011-03-16 11:05:33 +02001440The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001441failing example:
1442
1443 >>> def f(x):
1444 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001445 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001446 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001447 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001448 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001449 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001450 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001451 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001452 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001453 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001454 ... 500
1455 ... '''
1456 >>> test = doctest.DocTestFinder().find(f)[0]
1457 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1458 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001459 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001460 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001461 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001462 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001463 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001464 Expected:
1465 200
1466 Got:
1467 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001468 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001469
Ezio Melotti13925002011-03-16 11:05:33 +02001470However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001471
1472 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001473 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001474 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001475 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001476 Expecting:
1477 1
1478 ok
1479 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001480 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001481 Expecting:
1482 200
1483 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001484 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001485 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001486 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001487 Expected:
1488 200
1489 Got:
1490 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001491 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001492
R David Murray5a9d7062012-11-21 15:09:21 -05001493The FAIL_FAST flag causes the runner to exit after the first failing example,
1494so subsequent examples are not even attempted:
1495
1496 >>> flags = doctest.FAIL_FAST
1497 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1498 ... # doctest: +ELLIPSIS
1499 **********************************************************************
1500 File ..., line 5, in f
1501 Failed example:
1502 print(2) # first failure
1503 Expected:
1504 200
1505 Got:
1506 2
1507 TestResults(failed=1, attempted=2)
1508
1509Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1510FAIL_FAST only:
1511
1512 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1513 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1514 ... # doctest: +ELLIPSIS
1515 **********************************************************************
1516 File ..., line 5, in f
1517 Failed example:
1518 print(2) # first failure
1519 Expected:
1520 200
1521 Got:
1522 2
1523 TestResults(failed=1, attempted=2)
1524
1525For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1526exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001527
1528 >>> def f(x):
1529 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001530 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001531 ... 1
1532 ... >>> raise ValueError(2) # first failure
1533 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001534 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001535 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001536 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001537 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001538 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001539 ... 500
1540 ... '''
1541 >>> test = doctest.DocTestFinder().find(f)[0]
1542 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1543 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1544 ... # doctest: +ELLIPSIS
1545 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001546 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001547 Failed example:
1548 raise ValueError(2) # first failure
1549 Exception raised:
1550 ...
1551 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001552 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001553 >>> flags = doctest.FAIL_FAST
1554 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1555 ... # doctest: +ELLIPSIS
1556 **********************************************************************
1557 File ..., line 5, in f
1558 Failed example:
1559 raise ValueError(2) # first failure
1560 Exception raised:
1561 ...
1562 ValueError: 2
1563 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001564
Thomas Wouters477c8d52006-05-27 19:21:47 +00001565New option flags can also be registered, via register_optionflag(). Here
1566we reach into doctest's internals a bit.
1567
1568 >>> unlikely = "UNLIKELY_OPTION_NAME"
1569 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1570 False
1571 >>> new_flag_value = doctest.register_optionflag(unlikely)
1572 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1573 True
1574
1575Before 2.4.4/2.5, registering a name more than once erroneously created
1576more than one flag value. Here we verify that's fixed:
1577
1578 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1579 >>> redundant_flag_value == new_flag_value
1580 True
1581
1582Clean up.
1583 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1584
Tim Petersc6cbab02004-08-22 19:43:28 +00001585 """
1586
Tim Peters8485b562004-08-04 18:46:34 +00001587 def option_directives(): r"""
1588Tests of `DocTestRunner`'s option directive mechanism.
1589
Edward Loper74bca7a2004-08-12 02:27:44 +00001590Option directives can be used to turn option flags on or off for a
1591single example. To turn an option on for an example, follow that
1592example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001593
1594 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001595 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001596 ... [0, 1, ..., 9]
1597 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001598 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001599 ... [0, 1, ..., 9]
1600 ... '''
1601 >>> test = doctest.DocTestFinder().find(f)[0]
1602 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001603 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001604 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001605 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001606 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001607 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001608 Expected:
1609 [0, 1, ..., 9]
1610 Got:
1611 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001612 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001613
1614To turn an option off for an example, follow that example with a
1615comment of the form ``# doctest: -OPTION``:
1616
1617 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001618 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001619 ... [0, 1, ..., 9]
1620 ...
1621 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001622 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001623 ... [0, 1, ..., 9]
1624 ... '''
1625 >>> test = doctest.DocTestFinder().find(f)[0]
1626 >>> doctest.DocTestRunner(verbose=False,
1627 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001628 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001629 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001630 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001631 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001632 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001633 Expected:
1634 [0, 1, ..., 9]
1635 Got:
1636 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001637 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001638
1639Option directives affect only the example that they appear with; they
1640do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001641
Edward Loper74bca7a2004-08-12 02:27:44 +00001642 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001643 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001644 ... [0, 1, ..., 9]
1645 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001646 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001647 ... [0, 1, ..., 9]
1648 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001649 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001650 ... [0, 1, ..., 9]
1651 ... '''
1652 >>> test = doctest.DocTestFinder().find(f)[0]
1653 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001654 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001655 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001656 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001657 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001658 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001659 Expected:
1660 [0, 1, ..., 9]
1661 Got:
1662 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001663 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001664 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001665 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001666 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001667 Expected:
1668 [0, 1, ..., 9]
1669 Got:
1670 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001671 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001672
Edward Loper74bca7a2004-08-12 02:27:44 +00001673Multiple options may be modified by a single option directive. They
1674may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001675
1676 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001677 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001678 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001679 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001680 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001681 ... [0, 1, ..., 9]
1682 ... '''
1683 >>> test = doctest.DocTestFinder().find(f)[0]
1684 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001685 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001686 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001687 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001688 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001689 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001690 Expected:
1691 [0, 1, ..., 9]
1692 Got:
1693 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001694 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001695
1696 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001697 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001698 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001699 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001700 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1701 ... [0, 1, ..., 9]
1702 ... '''
1703 >>> test = doctest.DocTestFinder().find(f)[0]
1704 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001705 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001706 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001707 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001708 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001709 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001710 Expected:
1711 [0, 1, ..., 9]
1712 Got:
1713 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001714 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001715
1716 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001717 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001718 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001719 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001720 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1721 ... [0, 1, ..., 9]
1722 ... '''
1723 >>> test = doctest.DocTestFinder().find(f)[0]
1724 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001725 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001726 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001727 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001728 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001729 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001730 Expected:
1731 [0, 1, ..., 9]
1732 Got:
1733 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001734 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001735
1736The option directive may be put on the line following the source, as
1737long as a continuation prompt is used:
1738
1739 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001740 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001741 ... ... # doctest: +ELLIPSIS
1742 ... [0, 1, ..., 9]
1743 ... '''
1744 >>> test = doctest.DocTestFinder().find(f)[0]
1745 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001746 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001747
Edward Loper74bca7a2004-08-12 02:27:44 +00001748For examples with multi-line source, the option directive may appear
1749at the end of any line:
1750
1751 >>> def f(x): r'''
1752 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001753 ... ... print(' ', x, end='', sep='')
1754 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001755 ...
1756 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001757 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1758 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001759 ... '''
1760 >>> test = doctest.DocTestFinder().find(f)[0]
1761 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001762 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001763
1764If more than one line of an example with multi-line source has an
1765option directive, then they are combined:
1766
1767 >>> def f(x): r'''
1768 ... Should fail (option directive not on the last line):
1769 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001770 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001771 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001772 ... '''
1773 >>> test = doctest.DocTestFinder().find(f)[0]
1774 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001775 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001776
1777It is an error to have a comment of the form ``# doctest:`` that is
1778*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1779``OPTION`` is an option that has been registered with
1780`register_option`:
1781
1782 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001783 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001784 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1785 Traceback (most recent call last):
1786 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1787
1788 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001789 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001790 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1791 Traceback (most recent call last):
1792 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1793
1794It is an error to use an option directive on a line that contains no
1795source:
1796
1797 >>> s = '>>> # doctest: +ELLIPSIS'
1798 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1799 Traceback (most recent call last):
1800 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 +00001801"""
1802
1803def test_testsource(): r"""
1804Unit tests for `testsource()`.
1805
1806The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001807test with that name in that module, and converts it to a script. The
1808example code is converted to regular Python code. The surrounding
1809words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001810
1811 >>> import test.test_doctest
1812 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001813 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001814 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001815 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001816 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001817 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001818 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001819 #
Edward Lopera5db6002004-08-12 02:41:30 +00001820 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001821 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001822
1823 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001824 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001825 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001826 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001827 ## 1
1828 ## 2
1829 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001830 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001831
1832 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001833 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001834 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001835 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001836 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001837 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001838 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001839 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001840 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001841"""
1842
1843def test_debug(): r"""
1844
1845Create a docstring that we want to debug:
1846
1847 >>> s = '''
1848 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001849 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001850 ... 12
1851 ... '''
1852
1853Create some fake stdin input, to feed to the debugger:
1854
Tim Peters8485b562004-08-04 18:46:34 +00001855 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001856 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001857
1858Run the debugger on the docstring, and then restore sys.stdin.
1859
Edward Loper2de91ba2004-08-27 02:07:46 +00001860 >>> try: doctest.debug_src(s)
1861 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001863 (Pdb) next
1864 12
Tim Peters8485b562004-08-04 18:46:34 +00001865 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001866 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001867 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001868 12
1869 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001870
1871"""
1872
Brett Cannon31f59292011-02-21 19:29:56 +00001873if not hasattr(sys, 'gettrace') or not sys.gettrace():
1874 def test_pdb_set_trace():
1875 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001876
Brett Cannon31f59292011-02-21 19:29:56 +00001877 You can use pdb.set_trace from a doctest. To do so, you must
1878 retrieve the set_trace function from the pdb module at the time
1879 you use it. The doctest module changes sys.stdout so that it can
1880 capture program output. It also temporarily replaces pdb.set_trace
1881 with a version that restores stdout. This is necessary for you to
1882 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001883
Brett Cannon31f59292011-02-21 19:29:56 +00001884 >>> doc = '''
1885 ... >>> x = 42
1886 ... >>> raise Exception('clé')
1887 ... Traceback (most recent call last):
1888 ... Exception: clé
1889 ... >>> import pdb; pdb.set_trace()
1890 ... '''
1891 >>> parser = doctest.DocTestParser()
1892 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1893 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001894
Brett Cannon31f59292011-02-21 19:29:56 +00001895 To demonstrate this, we'll create a fake standard input that
1896 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001897
Brett Cannon31f59292011-02-21 19:29:56 +00001898 >>> real_stdin = sys.stdin
1899 >>> sys.stdin = _FakeInput([
1900 ... 'print(x)', # print data defined by the example
1901 ... 'continue', # stop debugging
1902 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001903
Brett Cannon31f59292011-02-21 19:29:56 +00001904 >>> try: runner.run(test)
1905 ... finally: sys.stdin = real_stdin
1906 --Return--
1907 > <doctest foo-bar@baz[2]>(1)<module>()->None
1908 -> import pdb; pdb.set_trace()
1909 (Pdb) print(x)
1910 42
1911 (Pdb) continue
1912 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001913
Brett Cannon31f59292011-02-21 19:29:56 +00001914 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001915
Brett Cannon31f59292011-02-21 19:29:56 +00001916 >>> def calls_set_trace():
1917 ... y=2
1918 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001919
Brett Cannon31f59292011-02-21 19:29:56 +00001920 >>> doc = '''
1921 ... >>> x=1
1922 ... >>> calls_set_trace()
1923 ... '''
1924 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1925 >>> real_stdin = sys.stdin
1926 >>> sys.stdin = _FakeInput([
1927 ... 'print(y)', # print data defined in the function
1928 ... 'up', # out of function
1929 ... 'print(x)', # print data defined by the example
1930 ... 'continue', # stop debugging
1931 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001932
Brett Cannon31f59292011-02-21 19:29:56 +00001933 >>> try:
1934 ... runner.run(test)
1935 ... finally:
1936 ... sys.stdin = real_stdin
1937 --Return--
Serhiy Storchakae437a102016-04-24 21:41:02 +03001938 > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
Brett Cannon31f59292011-02-21 19:29:56 +00001939 -> import pdb; pdb.set_trace()
1940 (Pdb) print(y)
1941 2
1942 (Pdb) up
1943 > <doctest foo-bar@baz[1]>(1)<module>()
1944 -> calls_set_trace()
1945 (Pdb) print(x)
1946 1
1947 (Pdb) continue
1948 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001949
Brett Cannon31f59292011-02-21 19:29:56 +00001950 During interactive debugging, source code is shown, even for
1951 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001952
Brett Cannon31f59292011-02-21 19:29:56 +00001953 >>> doc = '''
1954 ... >>> def f(x):
1955 ... ... g(x*2)
1956 ... >>> def g(x):
1957 ... ... print(x+3)
1958 ... ... import pdb; pdb.set_trace()
1959 ... >>> f(3)
1960 ... '''
1961 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1962 >>> real_stdin = sys.stdin
1963 >>> sys.stdin = _FakeInput([
1964 ... 'list', # list source from example 2
1965 ... 'next', # return from g()
1966 ... 'list', # list source from example 1
1967 ... 'next', # return from f()
1968 ... 'list', # list source from example 3
1969 ... 'continue', # stop debugging
1970 ... ''])
1971 >>> try: runner.run(test)
1972 ... finally: sys.stdin = real_stdin
1973 ... # doctest: +NORMALIZE_WHITESPACE
1974 --Return--
1975 > <doctest foo-bar@baz[1]>(3)g()->None
1976 -> import pdb; pdb.set_trace()
1977 (Pdb) list
1978 1 def g(x):
1979 2 print(x+3)
1980 3 -> import pdb; pdb.set_trace()
1981 [EOF]
1982 (Pdb) next
1983 --Return--
1984 > <doctest foo-bar@baz[0]>(2)f()->None
1985 -> g(x*2)
1986 (Pdb) list
1987 1 def f(x):
1988 2 -> g(x*2)
1989 [EOF]
1990 (Pdb) next
1991 --Return--
1992 > <doctest foo-bar@baz[2]>(1)<module>()->None
1993 -> f(3)
1994 (Pdb) list
1995 1 -> f(3)
1996 [EOF]
1997 (Pdb) continue
1998 **********************************************************************
1999 File "foo-bar@baz.py", line 7, in foo-bar@baz
2000 Failed example:
2001 f(3)
2002 Expected nothing
2003 Got:
2004 9
2005 TestResults(failed=1, attempted=3)
2006 """
Jim Fulton356fd192004-08-09 11:34:47 +00002007
Brett Cannon31f59292011-02-21 19:29:56 +00002008 def test_pdb_set_trace_nested():
2009 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00002010
Brett Cannon31f59292011-02-21 19:29:56 +00002011 >>> class C(object):
2012 ... def calls_set_trace(self):
2013 ... y = 1
2014 ... import pdb; pdb.set_trace()
2015 ... self.f1()
2016 ... y = 2
2017 ... def f1(self):
2018 ... x = 1
2019 ... self.f2()
2020 ... x = 2
2021 ... def f2(self):
2022 ... z = 1
2023 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002024
Brett Cannon31f59292011-02-21 19:29:56 +00002025 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002026
Brett Cannon31f59292011-02-21 19:29:56 +00002027 >>> doc = '''
2028 ... >>> a = 1
2029 ... >>> calls_set_trace()
2030 ... '''
2031 >>> parser = doctest.DocTestParser()
2032 >>> runner = doctest.DocTestRunner(verbose=False)
2033 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2034 >>> real_stdin = sys.stdin
2035 >>> sys.stdin = _FakeInput([
2036 ... 'print(y)', # print data defined in the function
2037 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2038 ... 'up', 'print(x)',
2039 ... 'up', 'print(y)',
2040 ... 'up', 'print(foo)',
2041 ... 'continue', # stop debugging
2042 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002043
Brett Cannon31f59292011-02-21 19:29:56 +00002044 >>> try:
2045 ... runner.run(test)
2046 ... finally:
2047 ... sys.stdin = real_stdin
2048 ... # doctest: +REPORT_NDIFF
2049 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2050 -> self.f1()
2051 (Pdb) print(y)
2052 1
2053 (Pdb) step
2054 --Call--
2055 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2056 -> def f1(self):
2057 (Pdb) step
2058 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2059 -> x = 1
2060 (Pdb) step
2061 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2062 -> self.f2()
2063 (Pdb) step
2064 --Call--
2065 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2066 -> def f2(self):
2067 (Pdb) step
2068 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2069 -> z = 1
2070 (Pdb) step
2071 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2072 -> z = 2
2073 (Pdb) print(z)
2074 1
2075 (Pdb) up
2076 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2077 -> self.f2()
2078 (Pdb) print(x)
2079 1
2080 (Pdb) up
2081 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2082 -> self.f1()
2083 (Pdb) print(y)
2084 1
2085 (Pdb) up
2086 > <doctest foo-bar@baz[1]>(1)<module>()
2087 -> calls_set_trace()
2088 (Pdb) print(foo)
2089 *** NameError: name 'foo' is not defined
2090 (Pdb) continue
2091 TestResults(failed=0, attempted=2)
2092 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002093
Tim Peters19397e52004-08-06 22:02:59 +00002094def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002095 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002096
2097 We create a Suite by providing a module. A module can be provided
2098 by passing a module object:
2099
2100 >>> import unittest
2101 >>> import test.sample_doctest
2102 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2103 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002104 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002105
2106 We can also supply the module by name:
2107
2108 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2109 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002110 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002111
R David Murray5abd76a2012-09-10 10:15:58 -04002112 The module need not contain any doctest examples:
2113
2114 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2115 >>> suite.run(unittest.TestResult())
2116 <unittest.result.TestResult run=0 errors=0 failures=0>
2117
R David Murray1976d9b2014-04-14 20:28:36 -04002118 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002119
R David Murray1976d9b2014-04-14 20:28:36 -04002120 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002121 >>> suite.run(unittest.TestResult())
2122 <unittest.result.TestResult run=0 errors=0 failures=0>
2123
Tim Peters19397e52004-08-06 22:02:59 +00002124 We can use the current module:
2125
2126 >>> suite = test.sample_doctest.test_suite()
2127 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002128 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002129
R David Murray1976d9b2014-04-14 20:28:36 -04002130 We can also provide a DocTestFinder:
2131
2132 >>> finder = doctest.DocTestFinder()
2133 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2134 ... test_finder=finder)
2135 >>> suite.run(unittest.TestResult())
2136 <unittest.result.TestResult run=9 errors=0 failures=4>
2137
2138 The DocTestFinder need not return any tests:
2139
2140 >>> finder = doctest.DocTestFinder()
2141 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2142 ... test_finder=finder)
2143 >>> suite.run(unittest.TestResult())
2144 <unittest.result.TestResult run=0 errors=0 failures=0>
2145
Tim Peters19397e52004-08-06 22:02:59 +00002146 We can supply global variables. If we pass globs, they will be
2147 used instead of the module globals. Here we'll pass an empty
2148 globals, triggering an extra error:
2149
2150 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2151 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002152 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002153
2154 Alternatively, we can provide extra globals. Here we'll make an
2155 error go away by providing an extra global variable:
2156
2157 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2158 ... extraglobs={'y': 1})
2159 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002160 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002161
2162 You can pass option flags. Here we'll cause an extra error
2163 by disabling the blank-line feature:
2164
2165 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002166 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002167 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002168 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002169
Tim Peters1e277ee2004-08-07 05:37:52 +00002170 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002171
Jim Fultonf54bad42004-08-28 14:57:56 +00002172 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002173 ... import test.test_doctest
2174 ... test.test_doctest.sillySetup = True
2175
Jim Fultonf54bad42004-08-28 14:57:56 +00002176 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002177 ... import test.test_doctest
2178 ... del test.test_doctest.sillySetup
2179
2180 Here, we installed a silly variable that the test expects:
2181
2182 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2183 ... setUp=setUp, tearDown=tearDown)
2184 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002185 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002186
2187 But the tearDown restores sanity:
2188
2189 >>> import test.test_doctest
2190 >>> test.test_doctest.sillySetup
2191 Traceback (most recent call last):
2192 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002193 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002194
Berker Peksag4882cac2015-04-14 09:30:01 +03002195 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002196 we'll use the setUp function to supply the missing variable y:
2197
2198 >>> def setUp(test):
2199 ... test.globs['y'] = 1
2200
2201 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2202 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002203 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002204
2205 Here, we didn't need to use a tearDown function because we
2206 modified the test globals, which are a copy of the
2207 sample_doctest module dictionary. The test globals are
2208 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002209 """
2210
2211def test_DocFileSuite():
2212 """We can test tests found in text files using a DocFileSuite.
2213
2214 We create a suite by providing the names of one or more text
2215 files that include examples:
2216
2217 >>> import unittest
2218 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002219 ... 'test_doctest2.txt',
2220 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002221 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002222 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002223
2224 The test files are looked for in the directory containing the
2225 calling module. A package keyword argument can be provided to
2226 specify a different relative location.
2227
2228 >>> import unittest
2229 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2230 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002231 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002232 ... package='test')
2233 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002234 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002235
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002236 Support for using a package's __loader__.get_data() is also
2237 provided.
2238
2239 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002240 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002241 >>> if not hasattr(test, '__loader__'):
2242 ... test.__loader__ = pkgutil.get_loader(test)
2243 ... added_loader = True
2244 >>> try:
2245 ... suite = doctest.DocFileSuite('test_doctest.txt',
2246 ... 'test_doctest2.txt',
2247 ... 'test_doctest4.txt',
2248 ... package='test')
2249 ... suite.run(unittest.TestResult())
2250 ... finally:
2251 ... if added_loader:
2252 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002253 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002254
Edward Loper0273f5b2004-09-18 20:27:04 +00002255 '/' should be used as a path separator. It will be converted
2256 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002257
2258 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2259 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002260 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002261
Edward Loper0273f5b2004-09-18 20:27:04 +00002262 If DocFileSuite is used from an interactive session, then files
2263 are resolved relative to the directory of sys.argv[0]:
2264
Christian Heimes45f9af32007-11-27 21:50:00 +00002265 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002266 >>> save_argv = sys.argv
2267 >>> sys.argv = [test.test_doctest.__file__]
2268 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002269 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002270 >>> sys.argv = save_argv
2271
Edward Loper052d0cd2004-09-19 17:19:33 +00002272 By setting `module_relative=False`, os-specific paths may be
2273 used (including absolute paths and paths relative to the
2274 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002275
2276 >>> # Get the absolute path of the test package.
2277 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2278 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2279
2280 >>> # Use it to find the absolute path of test_doctest.txt.
2281 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2282
Edward Loper052d0cd2004-09-19 17:19:33 +00002283 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002284 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002285 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002286
Edward Loper052d0cd2004-09-19 17:19:33 +00002287 It is an error to specify `package` when `module_relative=False`:
2288
2289 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2290 ... package='test')
2291 Traceback (most recent call last):
2292 ValueError: Package may only be specified for module-relative paths.
2293
Tim Peters19397e52004-08-06 22:02:59 +00002294 You can specify initial global variables:
2295
2296 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2297 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002298 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002299 ... globs={'favorite_color': 'blue'})
2300 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002301 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002302
2303 In this case, we supplied a missing favorite color. You can
2304 provide doctest options:
2305
2306 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2307 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002308 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002309 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2310 ... globs={'favorite_color': 'blue'})
2311 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002312 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002313
2314 And, you can provide setUp and tearDown functions:
2315
Jim Fultonf54bad42004-08-28 14:57:56 +00002316 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002317 ... import test.test_doctest
2318 ... test.test_doctest.sillySetup = True
2319
Jim Fultonf54bad42004-08-28 14:57:56 +00002320 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002321 ... import test.test_doctest
2322 ... del test.test_doctest.sillySetup
2323
2324 Here, we installed a silly variable that the test expects:
2325
2326 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2327 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002328 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002329 ... setUp=setUp, tearDown=tearDown)
2330 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002331 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002332
2333 But the tearDown restores sanity:
2334
2335 >>> import test.test_doctest
2336 >>> test.test_doctest.sillySetup
2337 Traceback (most recent call last):
2338 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002339 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002340
Berker Peksag4882cac2015-04-14 09:30:01 +03002341 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002342 Here, we'll use a setUp function to set the favorite color in
2343 test_doctest.txt:
2344
2345 >>> def setUp(test):
2346 ... test.globs['favorite_color'] = 'blue'
2347
2348 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2349 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002350 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002351
2352 Here, we didn't need to use a tearDown function because we
2353 modified the test globals. The test globals are
2354 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002355
Fred Drake7c404a42004-12-21 23:46:34 +00002356 Tests in a file run using `DocFileSuite` can also access the
2357 `__file__` global, which is set to the name of the file
2358 containing the tests:
2359
Benjamin Petersonab078e92016-07-13 21:13:29 -07002360 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
Fred Drake7c404a42004-12-21 23:46:34 +00002361 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002362 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002363
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002364 If the tests contain non-ASCII characters, we have to specify which
2365 encoding the file is encoded with. We do so by using the `encoding`
2366 parameter:
2367
2368 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2369 ... 'test_doctest2.txt',
2370 ... 'test_doctest4.txt',
2371 ... encoding='utf-8')
2372 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002373 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002374
Jim Fultonf54bad42004-08-28 14:57:56 +00002375 """
Tim Peters19397e52004-08-06 22:02:59 +00002376
Jim Fulton07a349c2004-08-22 14:10:00 +00002377def test_trailing_space_in_test():
2378 """
Tim Petersa7def722004-08-23 22:13:22 +00002379 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002380
Jim Fulton07a349c2004-08-22 14:10:00 +00002381 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002382 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002383 foo \n
2384 """
Tim Peters19397e52004-08-06 22:02:59 +00002385
Yury Selivanovb532df62014-12-08 15:00:05 -05002386class Wrapper:
2387 def __init__(self, func):
2388 self.func = func
2389 functools.update_wrapper(self, func)
2390
2391 def __call__(self, *args, **kwargs):
2392 self.func(*args, **kwargs)
2393
2394@Wrapper
2395def test_look_in_unwrapped():
2396 """
2397 Docstrings in wrapped functions must be detected as well.
2398
2399 >>> 'one other test'
2400 'one other test'
2401 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002402
2403def test_unittest_reportflags():
2404 """Default unittest reporting flags can be set to control reporting
2405
2406 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2407 only the first failure of each test. First, we'll look at the
2408 output without the flag. The file test_doctest.txt file has two
2409 tests. They both fail if blank lines are disabled:
2410
2411 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2412 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2413 >>> import unittest
2414 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002415 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002416 Traceback ...
2417 Failed example:
2418 favorite_color
2419 ...
2420 Failed example:
2421 if 1:
2422 ...
2423
2424 Note that we see both failures displayed.
2425
2426 >>> old = doctest.set_unittest_reportflags(
2427 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2428
2429 Now, when we run the test:
2430
2431 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002432 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002433 Traceback ...
2434 Failed example:
2435 favorite_color
2436 Exception raised:
2437 ...
2438 NameError: name 'favorite_color' is not defined
2439 <BLANKLINE>
2440 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002441
Jim Fultonf54bad42004-08-28 14:57:56 +00002442 We get only the first failure.
2443
2444 If we give any reporting options when we set up the tests,
2445 however:
2446
2447 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2448 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2449
2450 Then the default eporting options are ignored:
2451
2452 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002453 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002454 Traceback ...
2455 Failed example:
2456 favorite_color
2457 ...
2458 Failed example:
2459 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002460 print('a')
2461 print()
2462 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002463 Differences (ndiff with -expected +actual):
2464 a
2465 - <BLANKLINE>
2466 +
2467 b
2468 <BLANKLINE>
2469 <BLANKLINE>
2470
2471
2472 Test runners can restore the formatting flags after they run:
2473
2474 >>> ignored = doctest.set_unittest_reportflags(old)
2475
2476 """
2477
Edward Loper052d0cd2004-09-19 17:19:33 +00002478def test_testfile(): r"""
2479Tests for the `testfile()` function. This function runs all the
2480doctest examples in a given file. In its simple invokation, it is
2481called with the name of a file, which is taken to be relative to the
2482calling module. The return value is (#failures, #tests).
2483
Florent Xicluna59250852010-02-27 14:21:57 +00002484We don't want `-v` in sys.argv for these tests.
2485
2486 >>> save_argv = sys.argv
2487 >>> if '-v' in sys.argv:
2488 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2489
2490
Edward Loper052d0cd2004-09-19 17:19:33 +00002491 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2492 **********************************************************************
2493 File "...", line 6, in test_doctest.txt
2494 Failed example:
2495 favorite_color
2496 Exception raised:
2497 ...
2498 NameError: name 'favorite_color' is not defined
2499 **********************************************************************
2500 1 items had failures:
2501 1 of 2 in test_doctest.txt
2502 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002503 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002504 >>> doctest.master = None # Reset master.
2505
2506(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002507`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002508same name.)
2509
2510Globals may be specified with the `globs` and `extraglobs` parameters:
2511
2512 >>> globs = {'favorite_color': 'blue'}
2513 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002514 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002515 >>> doctest.master = None # Reset master.
2516
2517 >>> extraglobs = {'favorite_color': 'red'}
2518 >>> doctest.testfile('test_doctest.txt', globs=globs,
2519 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2520 **********************************************************************
2521 File "...", line 6, in test_doctest.txt
2522 Failed example:
2523 favorite_color
2524 Expected:
2525 'blue'
2526 Got:
2527 'red'
2528 **********************************************************************
2529 1 items had failures:
2530 1 of 2 in test_doctest.txt
2531 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002532 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002533 >>> doctest.master = None # Reset master.
2534
2535The file may be made relative to a given module or package, using the
2536optional `module_relative` parameter:
2537
2538 >>> doctest.testfile('test_doctest.txt', globs=globs,
2539 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002540 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002541 >>> doctest.master = None # Reset master.
2542
Ezio Melotti13925002011-03-16 11:05:33 +02002543Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002544
2545 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2546 Trying:
2547 favorite_color
2548 Expecting:
2549 'blue'
2550 ok
2551 Trying:
2552 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002553 print('a')
2554 print()
2555 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002556 Expecting:
2557 a
2558 <BLANKLINE>
2559 b
2560 ok
2561 1 items passed all tests:
2562 2 tests in test_doctest.txt
2563 2 tests in 1 items.
2564 2 passed and 0 failed.
2565 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002566 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002567 >>> doctest.master = None # Reset master.
2568
2569The name of the test may be specified with the optional `name`
2570parameter:
2571
2572 >>> doctest.testfile('test_doctest.txt', name='newname')
2573 ... # doctest: +ELLIPSIS
2574 **********************************************************************
2575 File "...", line 6, in newname
2576 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002577 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002578 >>> doctest.master = None # Reset master.
2579
Ezio Melotti13925002011-03-16 11:05:33 +02002580The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002581parameter:
2582
2583 >>> doctest.testfile('test_doctest.txt', report=False)
2584 ... # doctest: +ELLIPSIS
2585 **********************************************************************
2586 File "...", line 6, in test_doctest.txt
2587 Failed example:
2588 favorite_color
2589 Exception raised:
2590 ...
2591 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002592 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002593 >>> doctest.master = None # Reset master.
2594
2595The optional keyword argument `raise_on_error` can be used to raise an
2596exception on the first error (which may be useful for postmortem
2597debugging):
2598
2599 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2600 ... # doctest: +ELLIPSIS
2601 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002602 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002603 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002604
2605If the tests contain non-ASCII characters, the tests might fail, since
2606it's unknown which encoding is used. The encoding can be specified
2607using the optional keyword argument `encoding`:
2608
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002609 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002610 **********************************************************************
2611 File "...", line 7, in test_doctest4.txt
2612 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002613 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002614 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002615 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002616 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002617 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002618 **********************************************************************
2619 ...
2620 **********************************************************************
2621 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002622 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002623 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002624 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002625 >>> doctest.master = None # Reset master.
2626
2627 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002628 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002629 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002630
2631Test the verbose output:
2632
2633 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2634 Trying:
2635 'föö'
2636 Expecting:
2637 'f\xf6\xf6'
2638 ok
2639 Trying:
2640 'bÄ…r'
2641 Expecting:
2642 'b\u0105r'
2643 ok
2644 1 items passed all tests:
2645 2 tests in test_doctest4.txt
2646 2 tests in 1 items.
2647 2 passed and 0 failed.
2648 Test passed.
2649 TestResults(failed=0, attempted=2)
2650 >>> doctest.master = None # Reset master.
2651 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002652"""
2653
R David Murrayb48cb292014-10-02 22:42:42 -04002654def test_lineendings(): r"""
2655*nix systems use \n line endings, while Windows systems use \r\n. Python
2656handles this using universal newline mode for reading files. Let's make
2657sure doctest does so (issue 8473) by creating temporary test files using each
2658of the two line disciplines. One of the two will be the "wrong" one for the
2659platform the test is run on.
2660
2661Windows line endings first:
2662
2663 >>> import tempfile, os
2664 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002665 >>> with open(fn, 'wb') as f:
2666 ... 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 -04002667 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002668 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002669 TestResults(failed=0, attempted=1)
2670 >>> os.remove(fn)
2671
2672And now *nix line endings:
2673
2674 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002675 >>> with open(fn, 'wb') as f:
2676 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002677 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002678 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002679 TestResults(failed=0, attempted=1)
2680 >>> os.remove(fn)
2681
2682"""
2683
R. David Murray58641de2009-06-12 15:33:19 +00002684def test_testmod(): r"""
2685Tests for the testmod function. More might be useful, but for now we're just
2686testing the case raised by Issue 6195, where trying to doctest a C module would
2687fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2688out of the binary module.
2689
2690 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002691 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002692 TestResults(failed=0, attempted=0)
2693"""
2694
Victor Stinner9d396392010-10-16 21:54:59 +00002695try:
2696 os.fsencode("foo-bär@baz.py")
2697except UnicodeEncodeError:
2698 # Skip the test: the filesystem encoding is unable to encode the filename
2699 pass
2700else:
2701 def test_unicode(): """
2702Check doctest with a non-ascii filename:
2703
2704 >>> doc = '''
2705 ... >>> raise Exception('clé')
2706 ... '''
2707 ...
2708 >>> parser = doctest.DocTestParser()
2709 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2710 >>> test
2711 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2712 >>> runner = doctest.DocTestRunner(verbose=False)
2713 >>> runner.run(test) # doctest: +ELLIPSIS
2714 **********************************************************************
2715 File "foo-bär@baz.py", line 2, in foo-bär@baz
2716 Failed example:
2717 raise Exception('clé')
2718 Exception raised:
2719 Traceback (most recent call last):
2720 File ...
2721 compileflags, 1), test.globs)
2722 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2723 raise Exception('clé')
2724 Exception: clé
2725 TestResults(failed=1, attempted=1)
2726 """
2727
R David Murray5707d502013-06-23 14:24:13 -04002728def test_CLI(): r"""
2729The doctest module can be used to run doctests against an arbitrary file.
2730These tests test this CLI functionality.
2731
2732We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002733to a temp dir to run the command against. Due to a current limitation in
2734script_helpers, though, we need a little utility function to turn the returned
2735output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002736
R David Murray4af68982013-06-25 08:11:22 -04002737 >>> def normalize(s):
2738 ... return '\n'.join(s.decode().splitlines())
2739
R David Murray4af68982013-06-25 08:11:22 -04002740With those preliminaries out of the way, we'll start with a file with two
2741simple tests and no errors. We'll run both the unadorned doctest command, and
2742the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002743
Berker Peksagce643912015-05-06 06:33:17 +03002744 >>> from test.support import script_helper, temp_dir
2745 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002746 ... fn = os.path.join(tmpdir, 'myfile.doc')
2747 ... with open(fn, 'w') as f:
2748 ... _ = f.write('This is a very simple test file.\n')
2749 ... _ = f.write(' >>> 1 + 1\n')
2750 ... _ = f.write(' 2\n')
2751 ... _ = f.write(' >>> "a"\n')
2752 ... _ = f.write(" 'a'\n")
2753 ... _ = f.write('\n')
2754 ... _ = f.write('And that is it.\n')
2755 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002756 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002757 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002758 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002759
2760With no arguments and passing tests, we should get no output:
2761
2762 >>> rc1, out1, err1
2763 (0, b'', b'')
2764
2765With the verbose flag, we should see the test output, but no error output:
2766
2767 >>> rc2, err2
2768 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002769 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002770 Trying:
2771 1 + 1
2772 Expecting:
2773 2
2774 ok
2775 Trying:
2776 "a"
2777 Expecting:
2778 'a'
2779 ok
2780 1 items passed all tests:
2781 2 tests in myfile.doc
2782 2 tests in 1 items.
2783 2 passed and 0 failed.
2784 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002785
2786Now we'll write a couple files, one with three tests, the other a python module
2787with two tests, both of the files having "errors" in the tests that can be made
2788non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2789the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002790allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002791ability to process more than one file on the command line and, since the second
2792file ends in '.py', its handling of python module files (as opposed to straight
2793text files).
2794
Berker Peksagce643912015-05-06 06:33:17 +03002795 >>> from test.support import script_helper, temp_dir
2796 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002797 ... fn = os.path.join(tmpdir, 'myfile.doc')
2798 ... with open(fn, 'w') as f:
2799 ... _ = f.write('This is another simple test file.\n')
2800 ... _ = f.write(' >>> 1 + 1\n')
2801 ... _ = f.write(' 2\n')
2802 ... _ = f.write(' >>> "abcdef"\n')
2803 ... _ = f.write(" 'a...f'\n")
2804 ... _ = f.write(' >>> "ajkml"\n')
2805 ... _ = f.write(" 'a...l'\n")
2806 ... _ = f.write('\n')
2807 ... _ = f.write('And that is it.\n')
2808 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2809 ... with open(fn2, 'w') as f:
2810 ... _ = f.write('def test_func():\n')
2811 ... _ = f.write(' \"\"\"\n')
2812 ... _ = f.write(' This is simple python test function.\n')
2813 ... _ = f.write(' >>> 1 + 1\n')
2814 ... _ = f.write(' 2\n')
2815 ... _ = f.write(' >>> "abc def"\n')
2816 ... _ = f.write(" 'abc def'\n")
2817 ... _ = f.write("\n")
2818 ... _ = f.write(' \"\"\"\n')
R David Murray5707d502013-06-23 14:24:13 -04002819 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002820 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002821 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002822 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002823 ... rc3, out3, err3 = script_helper.assert_python_ok(
2824 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002825 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002826 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002827 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002828 ... rc5, out5, err5 = script_helper.assert_python_ok(
2829 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002830 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002831
2832Our first test run will show the errors from the first file (doctest stops if a
2833file has errors). Note that doctest test-run error output appears on stdout,
2834not stderr:
2835
2836 >>> rc1, err1
2837 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002838 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002839 **********************************************************************
2840 File "...myfile.doc", line 4, in myfile.doc
2841 Failed example:
2842 "abcdef"
2843 Expected:
2844 'a...f'
2845 Got:
2846 'abcdef'
2847 **********************************************************************
2848 File "...myfile.doc", line 6, in myfile.doc
2849 Failed example:
2850 "ajkml"
2851 Expected:
2852 'a...l'
2853 Got:
2854 'ajkml'
2855 **********************************************************************
2856 1 items had failures:
2857 2 of 3 in myfile.doc
2858 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002859
2860With -o ELLIPSIS specified, the second run, against just the first file, should
2861produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2862should the third, which ran against both files:
2863
2864 >>> rc2, out2, err2
2865 (0, b'', b'')
2866 >>> rc3, out3, err3
2867 (0, b'', b'')
2868
2869The fourth run uses FAIL_FAST, so we should see only one error:
2870
2871 >>> rc4, err4
2872 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002873 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002874 **********************************************************************
2875 File "...myfile.doc", line 4, in myfile.doc
2876 Failed example:
2877 "abcdef"
2878 Expected:
2879 'a...f'
2880 Got:
2881 'abcdef'
2882 **********************************************************************
2883 1 items had failures:
2884 1 of 2 in myfile.doc
2885 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002886
2887The fifth test uses verbose with the two options, so we should get verbose
2888success output for the tests in both files:
2889
2890 >>> rc5, err5
2891 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002892 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002893 Trying:
2894 1 + 1
2895 Expecting:
2896 2
2897 ok
2898 Trying:
2899 "abcdef"
2900 Expecting:
2901 'a...f'
2902 ok
2903 Trying:
2904 "ajkml"
2905 Expecting:
2906 'a...l'
2907 ok
2908 1 items passed all tests:
2909 3 tests in myfile.doc
2910 3 tests in 1 items.
2911 3 passed and 0 failed.
2912 Test passed.
2913 Trying:
2914 1 + 1
2915 Expecting:
2916 2
2917 ok
2918 Trying:
2919 "abc def"
2920 Expecting:
2921 'abc def'
2922 ok
2923 1 items had no tests:
2924 myfile2
2925 1 items passed all tests:
2926 2 tests in myfile2.test_func
2927 2 tests in 2 items.
2928 2 passed and 0 failed.
2929 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002930
2931We should also check some typical error cases.
2932
2933Invalid file name:
2934
2935 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002936 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04002937 >>> rc, out
2938 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002939 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002940 Traceback (most recent call last):
2941 ...
2942 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
2943
2944Invalid doctest option:
2945
2946 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002947 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04002948 >>> rc, out
2949 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04002950 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002951 usage...invalid...nosuchoption...
2952
2953"""
2954
Tim Peters8485b562004-08-04 18:46:34 +00002955######################################################################
2956## Main
2957######################################################################
2958
2959def test_main():
2960 # Check the doctest cases in doctest itself:
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02002961 ret = support.run_doctest(doctest, verbosity=True)
Victor Stinner931602a2016-03-25 12:48:17 +01002962
Tim Peters8485b562004-08-04 18:46:34 +00002963 # Check the doctest cases defined here:
2964 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002965 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002966
Miss Islington (bot)5a0c3982018-03-06 07:16:11 -08002967 # Run unittests
2968 support.run_unittest(__name__)
2969
2970
Tim Peters8485b562004-08-04 18:46:34 +00002971def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002972 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01002973 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00002974 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002975 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002976 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002977 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002978 r.write_results(show_missing=True, summary=True,
2979 coverdir=coverdir)
2980
2981if __name__ == '__main__':
2982 if '-c' in sys.argv:
2983 test_coverage('/tmp/doctest.cover')
2984 else:
2985 test_main()