blob: f0eb52881bcf287e16dd9527278c3006f5bbced2 [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
Tim Peters8485b562004-08-04 18:46:34 +000012
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'
691 os.mkdir(pkg_name)
692 mod = importlib.import_module(pkg_name)
693 assert doctest.DocTestFinder().find(mod) == []
694 os.rmdir(pkg_name)
695
696
Edward Loper00f8da72004-08-26 18:05:07 +0000697def test_DocTestParser(): r"""
698Unit tests for the `DocTestParser` class.
699
700DocTestParser is used to parse docstrings containing doctest examples.
701
702The `parse` method divides a docstring into examples and intervening
703text:
704
705 >>> s = '''
706 ... >>> x, y = 2, 3 # no output expected
707 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000708 ... ... print(x)
709 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000710 ... 2
711 ... 3
712 ...
713 ... Some text.
714 ... >>> x+y
715 ... 5
716 ... '''
717 >>> parser = doctest.DocTestParser()
718 >>> for piece in parser.parse(s):
719 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000720 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000721 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000722 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000723 Text: '\n'
724 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
725 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000726 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000727 Text: '\nSome text.\n'
728 Example: ('x+y\n', '5\n', 9)
729 Text: ''
730
731The `get_examples` method returns just the examples:
732
733 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000734 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000735 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000736 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000737 ('x+y\n', '5\n', 9)
738
739The `get_doctest` method creates a Test from the examples, along with the
740given arguments:
741
742 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
743 >>> (test.name, test.filename, test.lineno)
744 ('name', 'filename', 5)
745 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000746 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000747 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000748 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000749 ('x+y\n', '5\n', 9)
750"""
751
Tim Peters8485b562004-08-04 18:46:34 +0000752class test_DocTestRunner:
753 def basics(): r"""
754Unit tests for the `DocTestRunner` class.
755
756DocTestRunner is used to run DocTest test cases, and to accumulate
757statistics. Here's a simple DocTest case we can use:
758
759 >>> def f(x):
760 ... '''
761 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000762 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000763 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000764 ... >>> x//2
765 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000766 ... '''
767 >>> test = doctest.DocTestFinder().find(f)[0]
768
769The main DocTestRunner interface is the `run` method, which runs a
770given DocTest case in a given namespace (globs). It returns a tuple
771`(f,t)`, where `f` is the number of failed tests and `t` is the number
772of tried tests.
773
774 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000775 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000776
777If any example produces incorrect output, then the test runner reports
778the failure and proceeds to the next example:
779
780 >>> def f(x):
781 ... '''
782 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000783 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000784 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000785 ... >>> x//2
786 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000787 ... '''
788 >>> test = doctest.DocTestFinder().find(f)[0]
789 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000790 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000791 Trying:
792 x = 12
793 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000794 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000795 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000796 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000797 Expecting:
798 14
Tim Peters8485b562004-08-04 18:46:34 +0000799 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000800 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000801 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000802 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000803 Expected:
804 14
805 Got:
806 12
Edward Loperaacf0832004-08-26 01:19:50 +0000807 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000808 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000809 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000810 6
Tim Peters8485b562004-08-04 18:46:34 +0000811 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000812 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000813"""
814 def verbose_flag(): r"""
815The `verbose` flag makes the test runner generate more detailed
816output:
817
818 >>> def f(x):
819 ... '''
820 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000821 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000822 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000823 ... >>> x//2
824 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000825 ... '''
826 >>> test = doctest.DocTestFinder().find(f)[0]
827
828 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000829 Trying:
830 x = 12
831 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000832 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000833 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000834 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000835 Expecting:
836 12
Tim Peters8485b562004-08-04 18:46:34 +0000837 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000838 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000839 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000840 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000841 6
Tim Peters8485b562004-08-04 18:46:34 +0000842 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000843 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000844
845If the `verbose` flag is unspecified, then the output will be verbose
846iff `-v` appears in sys.argv:
847
848 >>> # Save the real sys.argv list.
849 >>> old_argv = sys.argv
850
851 >>> # If -v does not appear in sys.argv, then output isn't verbose.
852 >>> sys.argv = ['test']
853 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000854 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000855
856 >>> # If -v does appear in sys.argv, then output is verbose.
857 >>> sys.argv = ['test', '-v']
858 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000859 Trying:
860 x = 12
861 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000862 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000863 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000864 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000865 Expecting:
866 12
Tim Peters8485b562004-08-04 18:46:34 +0000867 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000868 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000869 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000870 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000871 6
Tim Peters8485b562004-08-04 18:46:34 +0000872 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000873 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000874
875 >>> # Restore sys.argv
876 >>> sys.argv = old_argv
877
878In the remaining examples, the test runner's verbosity will be
879explicitly set, to ensure that the test behavior is consistent.
880 """
881 def exceptions(): r"""
882Tests of `DocTestRunner`'s exception handling.
883
884An expected exception is specified with a traceback message. The
885lines between the first line and the type/value may be omitted or
886replaced with any other string:
887
888 >>> def f(x):
889 ... '''
890 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000891 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000892 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000893 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000894 ... '''
895 >>> test = doctest.DocTestFinder().find(f)[0]
896 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000897 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000898
Edward Loper19b19582004-08-25 23:07:03 +0000899An example may not generate output before it raises an exception; if
900it does, then the traceback message will not be recognized as
901signaling an expected exception, so the example will be reported as an
902unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000903
904 >>> def f(x):
905 ... '''
906 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000907 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000908 ... pre-exception output
909 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000910 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000911 ... '''
912 >>> test = doctest.DocTestFinder().find(f)[0]
913 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000914 ... # doctest: +ELLIPSIS
915 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000916 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000917 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000918 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000919 Exception raised:
920 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000921 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000922 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000923
924Exception messages may contain newlines:
925
926 >>> def f(x):
927 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000928 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000929 ... Traceback (most recent call last):
930 ... ValueError: multi
931 ... line
932 ... message
933 ... '''
934 >>> test = doctest.DocTestFinder().find(f)[0]
935 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000936 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000937
938If an exception is expected, but an exception with the wrong type or
939message is raised, then it is reported as a failure:
940
941 >>> def f(x):
942 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000943 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000944 ... Traceback (most recent call last):
945 ... ValueError: wrong message
946 ... '''
947 >>> test = doctest.DocTestFinder().find(f)[0]
948 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000949 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000950 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000951 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000952 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000953 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000954 Expected:
955 Traceback (most recent call last):
956 ValueError: wrong message
957 Got:
958 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000959 ...
Tim Peters8485b562004-08-04 18:46:34 +0000960 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000961 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000962
Tim Peters1fbf9c52004-09-04 17:21:02 +0000963However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
964detail:
965
966 >>> def f(x):
967 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000968 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000969 ... Traceback (most recent call last):
970 ... ValueError: wrong message
971 ... '''
972 >>> test = doctest.DocTestFinder().find(f)[0]
973 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000974 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000975
Nick Coghlan5e76e942010-06-12 13:42:46 +0000976IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
977between Python versions. For example, in Python 2.x, the module path of
978the exception is not in the output, but this will fail under Python 3:
979
980 >>> def f(x):
981 ... r'''
982 ... >>> from http.client import HTTPException
983 ... >>> raise HTTPException('message')
984 ... Traceback (most recent call last):
985 ... HTTPException: message
986 ... '''
987 >>> test = doctest.DocTestFinder().find(f)[0]
988 >>> doctest.DocTestRunner(verbose=False).run(test)
989 ... # doctest: +ELLIPSIS
990 **********************************************************************
991 File ..., line 4, in f
992 Failed example:
993 raise HTTPException('message')
994 Expected:
995 Traceback (most recent call last):
996 HTTPException: message
997 Got:
998 Traceback (most recent call last):
999 ...
1000 http.client.HTTPException: message
1001 TestResults(failed=1, attempted=2)
1002
1003But in Python 3 the module path is included, and therefore a test must look
1004like the following test to succeed in Python 3. But that test will fail under
1005Python 2.
1006
1007 >>> def f(x):
1008 ... r'''
1009 ... >>> from http.client import HTTPException
1010 ... >>> raise HTTPException('message')
1011 ... Traceback (most recent call last):
1012 ... http.client.HTTPException: message
1013 ... '''
1014 >>> test = doctest.DocTestFinder().find(f)[0]
1015 >>> doctest.DocTestRunner(verbose=False).run(test)
1016 TestResults(failed=0, attempted=2)
1017
1018However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1019(or its unexpected absence) will be ignored:
1020
1021 >>> def f(x):
1022 ... r'''
1023 ... >>> from http.client import HTTPException
1024 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1025 ... Traceback (most recent call last):
1026 ... HTTPException: message
1027 ... '''
1028 >>> test = doctest.DocTestFinder().find(f)[0]
1029 >>> doctest.DocTestRunner(verbose=False).run(test)
1030 TestResults(failed=0, attempted=2)
1031
1032The module path will be completely ignored, so two different module paths will
1033still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1034be used when exceptions have changed module.
1035
1036 >>> def f(x):
1037 ... r'''
1038 ... >>> from http.client import HTTPException
1039 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1040 ... Traceback (most recent call last):
1041 ... foo.bar.HTTPException: message
1042 ... '''
1043 >>> test = doctest.DocTestFinder().find(f)[0]
1044 >>> doctest.DocTestRunner(verbose=False).run(test)
1045 TestResults(failed=0, attempted=2)
1046
Tim Peters1fbf9c52004-09-04 17:21:02 +00001047But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1048
1049 >>> def f(x):
1050 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001051 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001052 ... Traceback (most recent call last):
1053 ... TypeError: wrong type
1054 ... '''
1055 >>> test = doctest.DocTestFinder().find(f)[0]
1056 >>> doctest.DocTestRunner(verbose=False).run(test)
1057 ... # doctest: +ELLIPSIS
1058 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001059 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001060 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001061 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001062 Expected:
1063 Traceback (most recent call last):
1064 TypeError: wrong type
1065 Got:
1066 Traceback (most recent call last):
1067 ...
1068 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001069 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001070
Tim Petersf9a07f22013-12-03 21:02:05 -06001071If the exception does not have a message, you can still use
1072IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1073
1074 >>> def f(x):
1075 ... r'''
1076 ... >>> from http.client import HTTPException
1077 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1078 ... Traceback (most recent call last):
1079 ... foo.bar.HTTPException
1080 ... '''
1081 >>> test = doctest.DocTestFinder().find(f)[0]
1082 >>> doctest.DocTestRunner(verbose=False).run(test)
1083 TestResults(failed=0, attempted=2)
1084
1085Note that a trailing colon doesn't matter either:
1086
1087 >>> def f(x):
1088 ... r'''
1089 ... >>> from http.client import HTTPException
1090 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1091 ... Traceback (most recent call last):
1092 ... foo.bar.HTTPException:
1093 ... '''
1094 >>> test = doctest.DocTestFinder().find(f)[0]
1095 >>> doctest.DocTestRunner(verbose=False).run(test)
1096 TestResults(failed=0, attempted=2)
1097
Tim Peters8485b562004-08-04 18:46:34 +00001098If an exception is raised but not expected, then it is reported as an
1099unexpected exception:
1100
Tim Peters8485b562004-08-04 18:46:34 +00001101 >>> def f(x):
1102 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001103 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001104 ... 0
1105 ... '''
1106 >>> test = doctest.DocTestFinder().find(f)[0]
1107 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001108 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001109 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001110 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001111 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001112 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001113 Exception raised:
1114 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001115 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001116 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001117 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001118"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001119 def displayhook(): r"""
1120Test that changing sys.displayhook doesn't matter for doctest.
1121
1122 >>> import sys
1123 >>> orig_displayhook = sys.displayhook
1124 >>> def my_displayhook(x):
1125 ... print('hi!')
1126 >>> sys.displayhook = my_displayhook
1127 >>> def f():
1128 ... '''
1129 ... >>> 3
1130 ... 3
1131 ... '''
1132 >>> test = doctest.DocTestFinder().find(f)[0]
1133 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1134 >>> post_displayhook = sys.displayhook
1135
1136 We need to restore sys.displayhook now, so that we'll be able to test
1137 results.
1138
1139 >>> sys.displayhook = orig_displayhook
1140
1141 Ok, now we can check that everything is ok.
1142
1143 >>> r
1144 TestResults(failed=0, attempted=1)
1145 >>> post_displayhook is my_displayhook
1146 True
1147"""
Tim Peters8485b562004-08-04 18:46:34 +00001148 def optionflags(): r"""
1149Tests of `DocTestRunner`'s option flag handling.
1150
1151Several option flags can be used to customize the behavior of the test
1152runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001153to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001154together).
1155
1156The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1157and 1/0:
1158
1159 >>> def f(x):
1160 ... '>>> True\n1\n'
1161
1162 >>> # Without the flag:
1163 >>> test = doctest.DocTestFinder().find(f)[0]
1164 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001165 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001166
1167 >>> # With the flag:
1168 >>> test = doctest.DocTestFinder().find(f)[0]
1169 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1170 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001171 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001172 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001173 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001174 Failed example:
1175 True
1176 Expected:
1177 1
1178 Got:
1179 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001180 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001181
1182The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1183and the '<BLANKLINE>' marker:
1184
1185 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001186 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001187
1188 >>> # Without the flag:
1189 >>> test = doctest.DocTestFinder().find(f)[0]
1190 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001191 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001192
1193 >>> # With the flag:
1194 >>> test = doctest.DocTestFinder().find(f)[0]
1195 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1196 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001197 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001198 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001199 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001200 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001201 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001202 Expected:
1203 a
1204 <BLANKLINE>
1205 b
1206 Got:
1207 a
1208 <BLANKLINE>
1209 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001210 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001211
1212The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1213treated as equal:
1214
1215 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001216 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001217
1218 >>> # Without the flag:
1219 >>> test = doctest.DocTestFinder().find(f)[0]
1220 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001221 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001222 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001223 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001224 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001225 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001226 Expected:
1227 1 2
1228 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001229 Got:
1230 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001231 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001232
1233 >>> # With the flag:
1234 >>> test = doctest.DocTestFinder().find(f)[0]
1235 >>> flags = doctest.NORMALIZE_WHITESPACE
1236 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001237 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001238
Tim Peters026f8dc2004-08-19 16:38:58 +00001239 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001240 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001241 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1242 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1243
Tim Peters8485b562004-08-04 18:46:34 +00001244The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1245output to match any substring in the actual output:
1246
1247 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001248 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001249
1250 >>> # Without the flag:
1251 >>> test = doctest.DocTestFinder().find(f)[0]
1252 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001253 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001254 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001255 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001256 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001257 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001258 Expected:
1259 [0, 1, 2, ..., 14]
1260 Got:
1261 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001262 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001263
1264 >>> # With the flag:
1265 >>> test = doctest.DocTestFinder().find(f)[0]
1266 >>> flags = doctest.ELLIPSIS
1267 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001268 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001269
Tim Peterse594bee2004-08-22 01:47:51 +00001270 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001271
Guido van Rossume0192e52007-02-09 23:39:59 +00001272 >>> if 1:
1273 ... for i in range(100):
1274 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1275 ... print('!')
1276 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001277
Tim Peters026f8dc2004-08-19 16:38:58 +00001278 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001279
Guido van Rossume0192e52007-02-09 23:39:59 +00001280 >>> if 1: #doctest: +ELLIPSIS
1281 ... for i in range(20):
1282 ... print(i, end=' ')
1283 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001284 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001285
Tim Peters026f8dc2004-08-19 16:38:58 +00001286 Examples from the docs:
1287
Guido van Rossum805365e2007-05-07 22:24:25 +00001288 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001289 [0, 1, ..., 18, 19]
1290
Guido van Rossum805365e2007-05-07 22:24:25 +00001291 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001292 ... # doctest: +NORMALIZE_WHITESPACE
1293 [0, 1, ..., 18, 19]
1294
Thomas Wouters477c8d52006-05-27 19:21:47 +00001295The SKIP flag causes an example to be skipped entirely. I.e., the
1296example is not run. It can be useful in contexts where doctest
1297examples serve as both documentation and test cases, and an example
1298should be included for documentation purposes, but should not be
1299checked (e.g., because its output is random, or depends on resources
1300which would be unavailable.) The SKIP flag can also be used for
1301'commenting out' broken examples.
1302
1303 >>> import unavailable_resource # doctest: +SKIP
1304 >>> unavailable_resource.do_something() # doctest: +SKIP
1305 >>> unavailable_resource.blow_up() # doctest: +SKIP
1306 Traceback (most recent call last):
1307 ...
1308 UncheckedBlowUpError: Nobody checks me.
1309
1310 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001311 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001312 0.721216923889
1313
Edward Loper71f55af2004-08-26 01:41:51 +00001314The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001315and actual outputs to be displayed using a unified diff:
1316
1317 >>> def f(x):
1318 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001319 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001320 ... a
1321 ... B
1322 ... c
1323 ... d
1324 ... f
1325 ... g
1326 ... h
1327 ... '''
1328
1329 >>> # Without the flag:
1330 >>> test = doctest.DocTestFinder().find(f)[0]
1331 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001332 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001333 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001334 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001335 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001336 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001337 Expected:
1338 a
1339 B
1340 c
1341 d
1342 f
1343 g
1344 h
1345 Got:
1346 a
1347 b
1348 c
1349 d
1350 e
1351 f
1352 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001353 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001354
1355 >>> # With the flag:
1356 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001357 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001358 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001359 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001360 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001361 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001362 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001363 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001364 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001365 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001366 a
1367 -B
1368 +b
1369 c
1370 d
1371 +e
1372 f
1373 g
1374 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001375 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001376
Edward Loper71f55af2004-08-26 01:41:51 +00001377The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001378and actual outputs to be displayed using a context diff:
1379
Edward Loper71f55af2004-08-26 01:41:51 +00001380 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001381 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001382 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001383 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001384 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001385 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001386 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001387 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001388 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001389 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001390 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001391 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001392 a
1393 ! B
1394 c
1395 d
1396 f
1397 g
1398 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001399 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001400 a
1401 ! b
1402 c
1403 d
1404 + e
1405 f
1406 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001407 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001408
1409
Edward Loper71f55af2004-08-26 01:41:51 +00001410The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001411used by the popular ndiff.py utility. This does intraline difference
1412marking, as well as interline differences.
1413
1414 >>> def f(x):
1415 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001416 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001417 ... a b c d e f g h i j k 1 m
1418 ... '''
1419 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001420 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001421 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001422 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001423 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001424 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001425 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001426 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001427 Differences (ndiff with -expected +actual):
1428 - a b c d e f g h i j k 1 m
1429 ? ^
1430 + a b c d e f g h i j k l m
1431 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001432 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001433
Ezio Melotti13925002011-03-16 11:05:33 +02001434The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001435failing example:
1436
1437 >>> def f(x):
1438 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001439 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001440 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001441 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001442 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001443 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001444 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001445 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001446 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001447 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001448 ... 500
1449 ... '''
1450 >>> test = doctest.DocTestFinder().find(f)[0]
1451 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1452 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001453 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001454 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001455 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001456 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001457 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001458 Expected:
1459 200
1460 Got:
1461 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001462 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001463
Ezio Melotti13925002011-03-16 11:05:33 +02001464However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001465
1466 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001467 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001468 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001469 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001470 Expecting:
1471 1
1472 ok
1473 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001474 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001475 Expecting:
1476 200
1477 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001478 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001479 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001480 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001481 Expected:
1482 200
1483 Got:
1484 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001485 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001486
R David Murray5a9d7062012-11-21 15:09:21 -05001487The FAIL_FAST flag causes the runner to exit after the first failing example,
1488so subsequent examples are not even attempted:
1489
1490 >>> flags = doctest.FAIL_FAST
1491 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1492 ... # doctest: +ELLIPSIS
1493 **********************************************************************
1494 File ..., line 5, in f
1495 Failed example:
1496 print(2) # first failure
1497 Expected:
1498 200
1499 Got:
1500 2
1501 TestResults(failed=1, attempted=2)
1502
1503Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1504FAIL_FAST only:
1505
1506 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1507 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1508 ... # doctest: +ELLIPSIS
1509 **********************************************************************
1510 File ..., line 5, in f
1511 Failed example:
1512 print(2) # first failure
1513 Expected:
1514 200
1515 Got:
1516 2
1517 TestResults(failed=1, attempted=2)
1518
1519For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1520exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001521
1522 >>> def f(x):
1523 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001524 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001525 ... 1
1526 ... >>> raise ValueError(2) # first failure
1527 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001528 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001529 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001530 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001531 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001532 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001533 ... 500
1534 ... '''
1535 >>> test = doctest.DocTestFinder().find(f)[0]
1536 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1537 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1538 ... # doctest: +ELLIPSIS
1539 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001540 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001541 Failed example:
1542 raise ValueError(2) # first failure
1543 Exception raised:
1544 ...
1545 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001546 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001547 >>> flags = doctest.FAIL_FAST
1548 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1549 ... # doctest: +ELLIPSIS
1550 **********************************************************************
1551 File ..., line 5, in f
1552 Failed example:
1553 raise ValueError(2) # first failure
1554 Exception raised:
1555 ...
1556 ValueError: 2
1557 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001558
Thomas Wouters477c8d52006-05-27 19:21:47 +00001559New option flags can also be registered, via register_optionflag(). Here
1560we reach into doctest's internals a bit.
1561
1562 >>> unlikely = "UNLIKELY_OPTION_NAME"
1563 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1564 False
1565 >>> new_flag_value = doctest.register_optionflag(unlikely)
1566 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1567 True
1568
1569Before 2.4.4/2.5, registering a name more than once erroneously created
1570more than one flag value. Here we verify that's fixed:
1571
1572 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1573 >>> redundant_flag_value == new_flag_value
1574 True
1575
1576Clean up.
1577 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1578
Tim Petersc6cbab02004-08-22 19:43:28 +00001579 """
1580
Tim Peters8485b562004-08-04 18:46:34 +00001581 def option_directives(): r"""
1582Tests of `DocTestRunner`'s option directive mechanism.
1583
Edward Loper74bca7a2004-08-12 02:27:44 +00001584Option directives can be used to turn option flags on or off for a
1585single example. To turn an option on for an example, follow that
1586example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001587
1588 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001589 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001590 ... [0, 1, ..., 9]
1591 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001592 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001593 ... [0, 1, ..., 9]
1594 ... '''
1595 >>> test = doctest.DocTestFinder().find(f)[0]
1596 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001597 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001598 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001599 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001600 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001601 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001602 Expected:
1603 [0, 1, ..., 9]
1604 Got:
1605 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001606 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001607
1608To turn an option off for an example, follow that example with a
1609comment of the form ``# doctest: -OPTION``:
1610
1611 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001612 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001613 ... [0, 1, ..., 9]
1614 ...
1615 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001616 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001617 ... [0, 1, ..., 9]
1618 ... '''
1619 >>> test = doctest.DocTestFinder().find(f)[0]
1620 >>> doctest.DocTestRunner(verbose=False,
1621 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001622 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001623 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001624 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001625 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001626 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001627 Expected:
1628 [0, 1, ..., 9]
1629 Got:
1630 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001631 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001632
1633Option directives affect only the example that they appear with; they
1634do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001635
Edward Loper74bca7a2004-08-12 02:27:44 +00001636 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001637 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001638 ... [0, 1, ..., 9]
1639 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001640 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001641 ... [0, 1, ..., 9]
1642 ...
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 ... '''
1646 >>> test = doctest.DocTestFinder().find(f)[0]
1647 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001648 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001649 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001650 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001651 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001652 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001653 Expected:
1654 [0, 1, ..., 9]
1655 Got:
1656 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001657 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001658 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001659 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001660 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001661 Expected:
1662 [0, 1, ..., 9]
1663 Got:
1664 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001665 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001666
Edward Loper74bca7a2004-08-12 02:27:44 +00001667Multiple options may be modified by a single option directive. They
1668may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001669
1670 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001671 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001672 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001673 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001674 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001675 ... [0, 1, ..., 9]
1676 ... '''
1677 >>> test = doctest.DocTestFinder().find(f)[0]
1678 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001679 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001680 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001681 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001682 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001683 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001684 Expected:
1685 [0, 1, ..., 9]
1686 Got:
1687 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001688 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001689
1690 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001691 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001692 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001693 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001694 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1695 ... [0, 1, ..., 9]
1696 ... '''
1697 >>> test = doctest.DocTestFinder().find(f)[0]
1698 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001699 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001700 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001701 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001702 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001703 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001704 Expected:
1705 [0, 1, ..., 9]
1706 Got:
1707 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001708 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001709
1710 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001711 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001712 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001713 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001714 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1715 ... [0, 1, ..., 9]
1716 ... '''
1717 >>> test = doctest.DocTestFinder().find(f)[0]
1718 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001719 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001720 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001721 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001722 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001723 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001724 Expected:
1725 [0, 1, ..., 9]
1726 Got:
1727 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001728 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001729
1730The option directive may be put on the line following the source, as
1731long as a continuation prompt is used:
1732
1733 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001734 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001735 ... ... # doctest: +ELLIPSIS
1736 ... [0, 1, ..., 9]
1737 ... '''
1738 >>> test = doctest.DocTestFinder().find(f)[0]
1739 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001740 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001741
Edward Loper74bca7a2004-08-12 02:27:44 +00001742For examples with multi-line source, the option directive may appear
1743at the end of any line:
1744
1745 >>> def f(x): r'''
1746 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001747 ... ... print(' ', x, end='', sep='')
1748 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001749 ...
1750 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001751 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1752 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001753 ... '''
1754 >>> test = doctest.DocTestFinder().find(f)[0]
1755 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001756 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001757
1758If more than one line of an example with multi-line source has an
1759option directive, then they are combined:
1760
1761 >>> def f(x): r'''
1762 ... Should fail (option directive not on the last line):
1763 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001764 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001765 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001766 ... '''
1767 >>> test = doctest.DocTestFinder().find(f)[0]
1768 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001769 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001770
1771It is an error to have a comment of the form ``# doctest:`` that is
1772*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1773``OPTION`` is an option that has been registered with
1774`register_option`:
1775
1776 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001777 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001778 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1779 Traceback (most recent call last):
1780 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1781
1782 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001783 >>> s = '>>> print(12) #doctest: ELLIPSIS'
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: 'ELLIPSIS'
1787
1788It is an error to use an option directive on a line that contains no
1789source:
1790
1791 >>> s = '>>> # doctest: +ELLIPSIS'
1792 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1793 Traceback (most recent call last):
1794 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 +00001795"""
1796
1797def test_testsource(): r"""
1798Unit tests for `testsource()`.
1799
1800The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001801test with that name in that module, and converts it to a script. The
1802example code is converted to regular Python code. The surrounding
1803words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001804
1805 >>> import test.test_doctest
1806 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001807 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001808 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001809 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001810 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001811 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001812 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001813 #
Edward Lopera5db6002004-08-12 02:41:30 +00001814 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001815 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001816
1817 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001818 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001819 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001820 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001821 ## 1
1822 ## 2
1823 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001824 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001825
1826 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001827 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001828 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001829 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001830 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001831 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001832 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001833 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001834 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001835"""
1836
1837def test_debug(): r"""
1838
1839Create a docstring that we want to debug:
1840
1841 >>> s = '''
1842 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001843 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001844 ... 12
1845 ... '''
1846
1847Create some fake stdin input, to feed to the debugger:
1848
Tim Peters8485b562004-08-04 18:46:34 +00001849 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001850 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001851
1852Run the debugger on the docstring, and then restore sys.stdin.
1853
Edward Loper2de91ba2004-08-27 02:07:46 +00001854 >>> try: doctest.debug_src(s)
1855 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001856 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001857 (Pdb) next
1858 12
Tim Peters8485b562004-08-04 18:46:34 +00001859 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001861 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001862 12
1863 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001864
1865"""
1866
Brett Cannon31f59292011-02-21 19:29:56 +00001867if not hasattr(sys, 'gettrace') or not sys.gettrace():
1868 def test_pdb_set_trace():
1869 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001870
Brett Cannon31f59292011-02-21 19:29:56 +00001871 You can use pdb.set_trace from a doctest. To do so, you must
1872 retrieve the set_trace function from the pdb module at the time
1873 you use it. The doctest module changes sys.stdout so that it can
1874 capture program output. It also temporarily replaces pdb.set_trace
1875 with a version that restores stdout. This is necessary for you to
1876 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001877
Brett Cannon31f59292011-02-21 19:29:56 +00001878 >>> doc = '''
1879 ... >>> x = 42
1880 ... >>> raise Exception('clé')
1881 ... Traceback (most recent call last):
1882 ... Exception: clé
1883 ... >>> import pdb; pdb.set_trace()
1884 ... '''
1885 >>> parser = doctest.DocTestParser()
1886 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1887 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001888
Brett Cannon31f59292011-02-21 19:29:56 +00001889 To demonstrate this, we'll create a fake standard input that
1890 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001891
Brett Cannon31f59292011-02-21 19:29:56 +00001892 >>> real_stdin = sys.stdin
1893 >>> sys.stdin = _FakeInput([
1894 ... 'print(x)', # print data defined by the example
1895 ... 'continue', # stop debugging
1896 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001897
Brett Cannon31f59292011-02-21 19:29:56 +00001898 >>> try: runner.run(test)
1899 ... finally: sys.stdin = real_stdin
1900 --Return--
1901 > <doctest foo-bar@baz[2]>(1)<module>()->None
1902 -> import pdb; pdb.set_trace()
1903 (Pdb) print(x)
1904 42
1905 (Pdb) continue
1906 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001907
Brett Cannon31f59292011-02-21 19:29:56 +00001908 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001909
Brett Cannon31f59292011-02-21 19:29:56 +00001910 >>> def calls_set_trace():
1911 ... y=2
1912 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001913
Brett Cannon31f59292011-02-21 19:29:56 +00001914 >>> doc = '''
1915 ... >>> x=1
1916 ... >>> calls_set_trace()
1917 ... '''
1918 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1919 >>> real_stdin = sys.stdin
1920 >>> sys.stdin = _FakeInput([
1921 ... 'print(y)', # print data defined in the function
1922 ... 'up', # out of function
1923 ... 'print(x)', # print data defined by the example
1924 ... 'continue', # stop debugging
1925 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001926
Brett Cannon31f59292011-02-21 19:29:56 +00001927 >>> try:
1928 ... runner.run(test)
1929 ... finally:
1930 ... sys.stdin = real_stdin
1931 --Return--
Serhiy Storchakae437a102016-04-24 21:41:02 +03001932 > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
Brett Cannon31f59292011-02-21 19:29:56 +00001933 -> import pdb; pdb.set_trace()
1934 (Pdb) print(y)
1935 2
1936 (Pdb) up
1937 > <doctest foo-bar@baz[1]>(1)<module>()
1938 -> calls_set_trace()
1939 (Pdb) print(x)
1940 1
1941 (Pdb) continue
1942 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001943
Brett Cannon31f59292011-02-21 19:29:56 +00001944 During interactive debugging, source code is shown, even for
1945 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001946
Brett Cannon31f59292011-02-21 19:29:56 +00001947 >>> doc = '''
1948 ... >>> def f(x):
1949 ... ... g(x*2)
1950 ... >>> def g(x):
1951 ... ... print(x+3)
1952 ... ... import pdb; pdb.set_trace()
1953 ... >>> f(3)
1954 ... '''
1955 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1956 >>> real_stdin = sys.stdin
1957 >>> sys.stdin = _FakeInput([
1958 ... 'list', # list source from example 2
1959 ... 'next', # return from g()
1960 ... 'list', # list source from example 1
1961 ... 'next', # return from f()
1962 ... 'list', # list source from example 3
1963 ... 'continue', # stop debugging
1964 ... ''])
1965 >>> try: runner.run(test)
1966 ... finally: sys.stdin = real_stdin
1967 ... # doctest: +NORMALIZE_WHITESPACE
1968 --Return--
1969 > <doctest foo-bar@baz[1]>(3)g()->None
1970 -> import pdb; pdb.set_trace()
1971 (Pdb) list
1972 1 def g(x):
1973 2 print(x+3)
1974 3 -> import pdb; pdb.set_trace()
1975 [EOF]
1976 (Pdb) next
1977 --Return--
1978 > <doctest foo-bar@baz[0]>(2)f()->None
1979 -> g(x*2)
1980 (Pdb) list
1981 1 def f(x):
1982 2 -> g(x*2)
1983 [EOF]
1984 (Pdb) next
1985 --Return--
1986 > <doctest foo-bar@baz[2]>(1)<module>()->None
1987 -> f(3)
1988 (Pdb) list
1989 1 -> f(3)
1990 [EOF]
1991 (Pdb) continue
1992 **********************************************************************
1993 File "foo-bar@baz.py", line 7, in foo-bar@baz
1994 Failed example:
1995 f(3)
1996 Expected nothing
1997 Got:
1998 9
1999 TestResults(failed=1, attempted=3)
2000 """
Jim Fulton356fd192004-08-09 11:34:47 +00002001
Brett Cannon31f59292011-02-21 19:29:56 +00002002 def test_pdb_set_trace_nested():
2003 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00002004
Brett Cannon31f59292011-02-21 19:29:56 +00002005 >>> class C(object):
2006 ... def calls_set_trace(self):
2007 ... y = 1
2008 ... import pdb; pdb.set_trace()
2009 ... self.f1()
2010 ... y = 2
2011 ... def f1(self):
2012 ... x = 1
2013 ... self.f2()
2014 ... x = 2
2015 ... def f2(self):
2016 ... z = 1
2017 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002018
Brett Cannon31f59292011-02-21 19:29:56 +00002019 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002020
Brett Cannon31f59292011-02-21 19:29:56 +00002021 >>> doc = '''
2022 ... >>> a = 1
2023 ... >>> calls_set_trace()
2024 ... '''
2025 >>> parser = doctest.DocTestParser()
2026 >>> runner = doctest.DocTestRunner(verbose=False)
2027 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2028 >>> real_stdin = sys.stdin
2029 >>> sys.stdin = _FakeInput([
2030 ... 'print(y)', # print data defined in the function
2031 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2032 ... 'up', 'print(x)',
2033 ... 'up', 'print(y)',
2034 ... 'up', 'print(foo)',
2035 ... 'continue', # stop debugging
2036 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002037
Brett Cannon31f59292011-02-21 19:29:56 +00002038 >>> try:
2039 ... runner.run(test)
2040 ... finally:
2041 ... sys.stdin = real_stdin
2042 ... # doctest: +REPORT_NDIFF
2043 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2044 -> self.f1()
2045 (Pdb) print(y)
2046 1
2047 (Pdb) step
2048 --Call--
2049 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2050 -> def f1(self):
2051 (Pdb) step
2052 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2053 -> x = 1
2054 (Pdb) step
2055 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2056 -> self.f2()
2057 (Pdb) step
2058 --Call--
2059 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2060 -> def f2(self):
2061 (Pdb) step
2062 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2063 -> z = 1
2064 (Pdb) step
2065 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2066 -> z = 2
2067 (Pdb) print(z)
2068 1
2069 (Pdb) up
2070 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2071 -> self.f2()
2072 (Pdb) print(x)
2073 1
2074 (Pdb) up
2075 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2076 -> self.f1()
2077 (Pdb) print(y)
2078 1
2079 (Pdb) up
2080 > <doctest foo-bar@baz[1]>(1)<module>()
2081 -> calls_set_trace()
2082 (Pdb) print(foo)
2083 *** NameError: name 'foo' is not defined
2084 (Pdb) continue
2085 TestResults(failed=0, attempted=2)
2086 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002087
Tim Peters19397e52004-08-06 22:02:59 +00002088def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002089 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002090
2091 We create a Suite by providing a module. A module can be provided
2092 by passing a module object:
2093
2094 >>> import unittest
2095 >>> import test.sample_doctest
2096 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2097 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002098 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002099
2100 We can also supply the module by name:
2101
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
R David Murray5abd76a2012-09-10 10:15:58 -04002106 The module need not contain any doctest examples:
2107
2108 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2109 >>> suite.run(unittest.TestResult())
2110 <unittest.result.TestResult run=0 errors=0 failures=0>
2111
R David Murray1976d9b2014-04-14 20:28:36 -04002112 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002113
R David Murray1976d9b2014-04-14 20:28:36 -04002114 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002115 >>> suite.run(unittest.TestResult())
2116 <unittest.result.TestResult run=0 errors=0 failures=0>
2117
Tim Peters19397e52004-08-06 22:02:59 +00002118 We can use the current module:
2119
2120 >>> suite = test.sample_doctest.test_suite()
2121 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002122 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002123
R David Murray1976d9b2014-04-14 20:28:36 -04002124 We can also provide a DocTestFinder:
2125
2126 >>> finder = doctest.DocTestFinder()
2127 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2128 ... test_finder=finder)
2129 >>> suite.run(unittest.TestResult())
2130 <unittest.result.TestResult run=9 errors=0 failures=4>
2131
2132 The DocTestFinder need not return any tests:
2133
2134 >>> finder = doctest.DocTestFinder()
2135 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2136 ... test_finder=finder)
2137 >>> suite.run(unittest.TestResult())
2138 <unittest.result.TestResult run=0 errors=0 failures=0>
2139
Tim Peters19397e52004-08-06 22:02:59 +00002140 We can supply global variables. If we pass globs, they will be
2141 used instead of the module globals. Here we'll pass an empty
2142 globals, triggering an extra error:
2143
2144 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2145 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002146 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002147
2148 Alternatively, we can provide extra globals. Here we'll make an
2149 error go away by providing an extra global variable:
2150
2151 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2152 ... extraglobs={'y': 1})
2153 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002154 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002155
2156 You can pass option flags. Here we'll cause an extra error
2157 by disabling the blank-line feature:
2158
2159 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002160 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002161 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002162 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002163
Tim Peters1e277ee2004-08-07 05:37:52 +00002164 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002165
Jim Fultonf54bad42004-08-28 14:57:56 +00002166 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002167 ... import test.test_doctest
2168 ... test.test_doctest.sillySetup = True
2169
Jim Fultonf54bad42004-08-28 14:57:56 +00002170 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002171 ... import test.test_doctest
2172 ... del test.test_doctest.sillySetup
2173
2174 Here, we installed a silly variable that the test expects:
2175
2176 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2177 ... setUp=setUp, tearDown=tearDown)
2178 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002179 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002180
2181 But the tearDown restores sanity:
2182
2183 >>> import test.test_doctest
2184 >>> test.test_doctest.sillySetup
2185 Traceback (most recent call last):
2186 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002187 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002188
Berker Peksag4882cac2015-04-14 09:30:01 +03002189 The setUp and tearDown functions are passed test objects. Here
Jim Fultonf54bad42004-08-28 14:57:56 +00002190 we'll use the setUp function to supply the missing variable y:
2191
2192 >>> def setUp(test):
2193 ... test.globs['y'] = 1
2194
2195 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2196 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002197 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002198
2199 Here, we didn't need to use a tearDown function because we
2200 modified the test globals, which are a copy of the
2201 sample_doctest module dictionary. The test globals are
2202 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002203 """
2204
2205def test_DocFileSuite():
2206 """We can test tests found in text files using a DocFileSuite.
2207
2208 We create a suite by providing the names of one or more text
2209 files that include examples:
2210
2211 >>> import unittest
2212 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002213 ... 'test_doctest2.txt',
2214 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002215 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002216 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002217
2218 The test files are looked for in the directory containing the
2219 calling module. A package keyword argument can be provided to
2220 specify a different relative location.
2221
2222 >>> import unittest
2223 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2224 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002225 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002226 ... package='test')
2227 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002228 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002229
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002230 Support for using a package's __loader__.get_data() is also
2231 provided.
2232
2233 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002234 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002235 >>> if not hasattr(test, '__loader__'):
2236 ... test.__loader__ = pkgutil.get_loader(test)
2237 ... added_loader = True
2238 >>> try:
2239 ... suite = doctest.DocFileSuite('test_doctest.txt',
2240 ... 'test_doctest2.txt',
2241 ... 'test_doctest4.txt',
2242 ... package='test')
2243 ... suite.run(unittest.TestResult())
2244 ... finally:
2245 ... if added_loader:
2246 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002247 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002248
Edward Loper0273f5b2004-09-18 20:27:04 +00002249 '/' should be used as a path separator. It will be converted
2250 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002251
2252 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2253 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002254 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002255
Edward Loper0273f5b2004-09-18 20:27:04 +00002256 If DocFileSuite is used from an interactive session, then files
2257 are resolved relative to the directory of sys.argv[0]:
2258
Christian Heimes45f9af32007-11-27 21:50:00 +00002259 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002260 >>> save_argv = sys.argv
2261 >>> sys.argv = [test.test_doctest.__file__]
2262 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002263 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002264 >>> sys.argv = save_argv
2265
Edward Loper052d0cd2004-09-19 17:19:33 +00002266 By setting `module_relative=False`, os-specific paths may be
2267 used (including absolute paths and paths relative to the
2268 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002269
2270 >>> # Get the absolute path of the test package.
2271 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2272 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2273
2274 >>> # Use it to find the absolute path of test_doctest.txt.
2275 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2276
Edward Loper052d0cd2004-09-19 17:19:33 +00002277 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002278 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002279 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002280
Edward Loper052d0cd2004-09-19 17:19:33 +00002281 It is an error to specify `package` when `module_relative=False`:
2282
2283 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2284 ... package='test')
2285 Traceback (most recent call last):
2286 ValueError: Package may only be specified for module-relative paths.
2287
Tim Peters19397e52004-08-06 22:02:59 +00002288 You can specify initial global variables:
2289
2290 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2291 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002292 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002293 ... globs={'favorite_color': 'blue'})
2294 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002295 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002296
2297 In this case, we supplied a missing favorite color. You can
2298 provide doctest options:
2299
2300 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2301 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002302 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002303 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2304 ... globs={'favorite_color': 'blue'})
2305 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002306 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002307
2308 And, you can provide setUp and tearDown functions:
2309
Jim Fultonf54bad42004-08-28 14:57:56 +00002310 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002311 ... import test.test_doctest
2312 ... test.test_doctest.sillySetup = True
2313
Jim Fultonf54bad42004-08-28 14:57:56 +00002314 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002315 ... import test.test_doctest
2316 ... del test.test_doctest.sillySetup
2317
2318 Here, we installed a silly variable that the test expects:
2319
2320 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2321 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002322 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002323 ... setUp=setUp, tearDown=tearDown)
2324 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002325 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002326
2327 But the tearDown restores sanity:
2328
2329 >>> import test.test_doctest
2330 >>> test.test_doctest.sillySetup
2331 Traceback (most recent call last):
2332 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002333 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002334
Berker Peksag4882cac2015-04-14 09:30:01 +03002335 The setUp and tearDown functions are passed test objects.
Jim Fultonf54bad42004-08-28 14:57:56 +00002336 Here, we'll use a setUp function to set the favorite color in
2337 test_doctest.txt:
2338
2339 >>> def setUp(test):
2340 ... test.globs['favorite_color'] = 'blue'
2341
2342 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2343 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002344 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002345
2346 Here, we didn't need to use a tearDown function because we
2347 modified the test globals. The test globals are
2348 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002349
Fred Drake7c404a42004-12-21 23:46:34 +00002350 Tests in a file run using `DocFileSuite` can also access the
2351 `__file__` global, which is set to the name of the file
2352 containing the tests:
2353
Benjamin Petersonab078e92016-07-13 21:13:29 -07002354 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
Fred Drake7c404a42004-12-21 23:46:34 +00002355 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002356 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002357
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002358 If the tests contain non-ASCII characters, we have to specify which
2359 encoding the file is encoded with. We do so by using the `encoding`
2360 parameter:
2361
2362 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2363 ... 'test_doctest2.txt',
2364 ... 'test_doctest4.txt',
2365 ... encoding='utf-8')
2366 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002367 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002368
Jim Fultonf54bad42004-08-28 14:57:56 +00002369 """
Tim Peters19397e52004-08-06 22:02:59 +00002370
Jim Fulton07a349c2004-08-22 14:10:00 +00002371def test_trailing_space_in_test():
2372 """
Tim Petersa7def722004-08-23 22:13:22 +00002373 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002374
Jim Fulton07a349c2004-08-22 14:10:00 +00002375 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002376 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002377 foo \n
2378 """
Tim Peters19397e52004-08-06 22:02:59 +00002379
Yury Selivanovb532df62014-12-08 15:00:05 -05002380class Wrapper:
2381 def __init__(self, func):
2382 self.func = func
2383 functools.update_wrapper(self, func)
2384
2385 def __call__(self, *args, **kwargs):
2386 self.func(*args, **kwargs)
2387
2388@Wrapper
2389def test_look_in_unwrapped():
2390 """
2391 Docstrings in wrapped functions must be detected as well.
2392
2393 >>> 'one other test'
2394 'one other test'
2395 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002396
2397def test_unittest_reportflags():
2398 """Default unittest reporting flags can be set to control reporting
2399
2400 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2401 only the first failure of each test. First, we'll look at the
2402 output without the flag. The file test_doctest.txt file has two
2403 tests. They both fail if blank lines are disabled:
2404
2405 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2406 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2407 >>> import unittest
2408 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002409 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002410 Traceback ...
2411 Failed example:
2412 favorite_color
2413 ...
2414 Failed example:
2415 if 1:
2416 ...
2417
2418 Note that we see both failures displayed.
2419
2420 >>> old = doctest.set_unittest_reportflags(
2421 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2422
2423 Now, when we run the test:
2424
2425 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002426 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002427 Traceback ...
2428 Failed example:
2429 favorite_color
2430 Exception raised:
2431 ...
2432 NameError: name 'favorite_color' is not defined
2433 <BLANKLINE>
2434 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002435
Jim Fultonf54bad42004-08-28 14:57:56 +00002436 We get only the first failure.
2437
2438 If we give any reporting options when we set up the tests,
2439 however:
2440
2441 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2442 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2443
2444 Then the default eporting options are ignored:
2445
2446 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002447 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002448 Traceback ...
2449 Failed example:
2450 favorite_color
2451 ...
2452 Failed example:
2453 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002454 print('a')
2455 print()
2456 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002457 Differences (ndiff with -expected +actual):
2458 a
2459 - <BLANKLINE>
2460 +
2461 b
2462 <BLANKLINE>
2463 <BLANKLINE>
2464
2465
2466 Test runners can restore the formatting flags after they run:
2467
2468 >>> ignored = doctest.set_unittest_reportflags(old)
2469
2470 """
2471
Edward Loper052d0cd2004-09-19 17:19:33 +00002472def test_testfile(): r"""
2473Tests for the `testfile()` function. This function runs all the
2474doctest examples in a given file. In its simple invokation, it is
2475called with the name of a file, which is taken to be relative to the
2476calling module. The return value is (#failures, #tests).
2477
Florent Xicluna59250852010-02-27 14:21:57 +00002478We don't want `-v` in sys.argv for these tests.
2479
2480 >>> save_argv = sys.argv
2481 >>> if '-v' in sys.argv:
2482 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2483
2484
Edward Loper052d0cd2004-09-19 17:19:33 +00002485 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2486 **********************************************************************
2487 File "...", line 6, in test_doctest.txt
2488 Failed example:
2489 favorite_color
2490 Exception raised:
2491 ...
2492 NameError: name 'favorite_color' is not defined
2493 **********************************************************************
2494 1 items had failures:
2495 1 of 2 in test_doctest.txt
2496 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002497 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002498 >>> doctest.master = None # Reset master.
2499
2500(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002501`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002502same name.)
2503
2504Globals may be specified with the `globs` and `extraglobs` parameters:
2505
2506 >>> globs = {'favorite_color': 'blue'}
2507 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002508 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002509 >>> doctest.master = None # Reset master.
2510
2511 >>> extraglobs = {'favorite_color': 'red'}
2512 >>> doctest.testfile('test_doctest.txt', globs=globs,
2513 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2514 **********************************************************************
2515 File "...", line 6, in test_doctest.txt
2516 Failed example:
2517 favorite_color
2518 Expected:
2519 'blue'
2520 Got:
2521 'red'
2522 **********************************************************************
2523 1 items had failures:
2524 1 of 2 in test_doctest.txt
2525 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002526 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002527 >>> doctest.master = None # Reset master.
2528
2529The file may be made relative to a given module or package, using the
2530optional `module_relative` parameter:
2531
2532 >>> doctest.testfile('test_doctest.txt', globs=globs,
2533 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002534 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002535 >>> doctest.master = None # Reset master.
2536
Ezio Melotti13925002011-03-16 11:05:33 +02002537Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002538
2539 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2540 Trying:
2541 favorite_color
2542 Expecting:
2543 'blue'
2544 ok
2545 Trying:
2546 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002547 print('a')
2548 print()
2549 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002550 Expecting:
2551 a
2552 <BLANKLINE>
2553 b
2554 ok
2555 1 items passed all tests:
2556 2 tests in test_doctest.txt
2557 2 tests in 1 items.
2558 2 passed and 0 failed.
2559 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002560 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002561 >>> doctest.master = None # Reset master.
2562
2563The name of the test may be specified with the optional `name`
2564parameter:
2565
2566 >>> doctest.testfile('test_doctest.txt', name='newname')
2567 ... # doctest: +ELLIPSIS
2568 **********************************************************************
2569 File "...", line 6, in newname
2570 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002571 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002572 >>> doctest.master = None # Reset master.
2573
Ezio Melotti13925002011-03-16 11:05:33 +02002574The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002575parameter:
2576
2577 >>> doctest.testfile('test_doctest.txt', report=False)
2578 ... # doctest: +ELLIPSIS
2579 **********************************************************************
2580 File "...", line 6, in test_doctest.txt
2581 Failed example:
2582 favorite_color
2583 Exception raised:
2584 ...
2585 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002586 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002587 >>> doctest.master = None # Reset master.
2588
2589The optional keyword argument `raise_on_error` can be used to raise an
2590exception on the first error (which may be useful for postmortem
2591debugging):
2592
2593 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2594 ... # doctest: +ELLIPSIS
2595 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002596 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002597 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002598
2599If the tests contain non-ASCII characters, the tests might fail, since
2600it's unknown which encoding is used. The encoding can be specified
2601using the optional keyword argument `encoding`:
2602
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002603 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002604 **********************************************************************
2605 File "...", line 7, in test_doctest4.txt
2606 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002607 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002608 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002609 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002610 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002611 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002612 **********************************************************************
2613 ...
2614 **********************************************************************
2615 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002616 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002617 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002618 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002619 >>> doctest.master = None # Reset master.
2620
2621 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002622 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002623 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002624
2625Test the verbose output:
2626
2627 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2628 Trying:
2629 'föö'
2630 Expecting:
2631 'f\xf6\xf6'
2632 ok
2633 Trying:
2634 'bÄ…r'
2635 Expecting:
2636 'b\u0105r'
2637 ok
2638 1 items passed all tests:
2639 2 tests in test_doctest4.txt
2640 2 tests in 1 items.
2641 2 passed and 0 failed.
2642 Test passed.
2643 TestResults(failed=0, attempted=2)
2644 >>> doctest.master = None # Reset master.
2645 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002646"""
2647
R David Murrayb48cb292014-10-02 22:42:42 -04002648def test_lineendings(): r"""
2649*nix systems use \n line endings, while Windows systems use \r\n. Python
2650handles this using universal newline mode for reading files. Let's make
2651sure doctest does so (issue 8473) by creating temporary test files using each
2652of the two line disciplines. One of the two will be the "wrong" one for the
2653platform the test is run on.
2654
2655Windows line endings first:
2656
2657 >>> import tempfile, os
2658 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002659 >>> with open(fn, 'wb') as f:
2660 ... 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 -04002661 35
Victor Stinner09a08de2015-12-02 14:37:17 +01002662 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002663 TestResults(failed=0, attempted=1)
2664 >>> os.remove(fn)
2665
2666And now *nix line endings:
2667
2668 >>> fn = tempfile.mktemp()
Serhiy Storchakac9ba38c2015-04-04 10:36:25 +03002669 >>> with open(fn, 'wb') as f:
2670 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
R David Murrayb48cb292014-10-02 22:42:42 -04002671 30
Victor Stinner09a08de2015-12-02 14:37:17 +01002672 >>> doctest.testfile(fn, module_relative=False, verbose=False)
R David Murrayb48cb292014-10-02 22:42:42 -04002673 TestResults(failed=0, attempted=1)
2674 >>> os.remove(fn)
2675
2676"""
2677
R. David Murray58641de2009-06-12 15:33:19 +00002678def test_testmod(): r"""
2679Tests for the testmod function. More might be useful, but for now we're just
2680testing the case raised by Issue 6195, where trying to doctest a C module would
2681fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2682out of the binary module.
2683
2684 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002685 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002686 TestResults(failed=0, attempted=0)
2687"""
2688
Victor Stinner9d396392010-10-16 21:54:59 +00002689try:
2690 os.fsencode("foo-bär@baz.py")
2691except UnicodeEncodeError:
2692 # Skip the test: the filesystem encoding is unable to encode the filename
2693 pass
2694else:
2695 def test_unicode(): """
2696Check doctest with a non-ascii filename:
2697
2698 >>> doc = '''
2699 ... >>> raise Exception('clé')
2700 ... '''
2701 ...
2702 >>> parser = doctest.DocTestParser()
2703 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2704 >>> test
2705 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2706 >>> runner = doctest.DocTestRunner(verbose=False)
2707 >>> runner.run(test) # doctest: +ELLIPSIS
2708 **********************************************************************
2709 File "foo-bär@baz.py", line 2, in foo-bär@baz
2710 Failed example:
2711 raise Exception('clé')
2712 Exception raised:
2713 Traceback (most recent call last):
2714 File ...
2715 compileflags, 1), test.globs)
2716 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2717 raise Exception('clé')
2718 Exception: clé
2719 TestResults(failed=1, attempted=1)
2720 """
2721
R David Murray5707d502013-06-23 14:24:13 -04002722def test_CLI(): r"""
2723The doctest module can be used to run doctests against an arbitrary file.
2724These tests test this CLI functionality.
2725
2726We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002727to a temp dir to run the command against. Due to a current limitation in
2728script_helpers, though, we need a little utility function to turn the returned
2729output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002730
R David Murray4af68982013-06-25 08:11:22 -04002731 >>> def normalize(s):
2732 ... return '\n'.join(s.decode().splitlines())
2733
R David Murray4af68982013-06-25 08:11:22 -04002734With those preliminaries out of the way, we'll start with a file with two
2735simple tests and no errors. We'll run both the unadorned doctest command, and
2736the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002737
Berker Peksagce643912015-05-06 06:33:17 +03002738 >>> from test.support import script_helper, temp_dir
2739 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002740 ... fn = os.path.join(tmpdir, 'myfile.doc')
2741 ... with open(fn, 'w') as f:
2742 ... _ = f.write('This is a very simple test file.\n')
2743 ... _ = f.write(' >>> 1 + 1\n')
2744 ... _ = f.write(' 2\n')
2745 ... _ = f.write(' >>> "a"\n')
2746 ... _ = f.write(" 'a'\n")
2747 ... _ = f.write('\n')
2748 ... _ = f.write('And that is it.\n')
2749 ... rc1, out1, err1 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002750 ... '-m', 'doctest', fn)
R David Murray5707d502013-06-23 14:24:13 -04002751 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002752 ... '-m', 'doctest', '-v', fn)
R David Murray5707d502013-06-23 14:24:13 -04002753
2754With no arguments and passing tests, we should get no output:
2755
2756 >>> rc1, out1, err1
2757 (0, b'', b'')
2758
2759With the verbose flag, we should see the test output, but no error output:
2760
2761 >>> rc2, err2
2762 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002763 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002764 Trying:
2765 1 + 1
2766 Expecting:
2767 2
2768 ok
2769 Trying:
2770 "a"
2771 Expecting:
2772 'a'
2773 ok
2774 1 items passed all tests:
2775 2 tests in myfile.doc
2776 2 tests in 1 items.
2777 2 passed and 0 failed.
2778 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002779
2780Now we'll write a couple files, one with three tests, the other a python module
2781with two tests, both of the files having "errors" in the tests that can be made
2782non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2783the first file, NORMALIZE_WHITESPACE in the second). This combination will
Martin Panterc04fb562016-02-10 05:44:01 +00002784allow thoroughly testing the -f and -o flags, as well as the doctest command's
R David Murray5707d502013-06-23 14:24:13 -04002785ability to process more than one file on the command line and, since the second
2786file ends in '.py', its handling of python module files (as opposed to straight
2787text files).
2788
Berker Peksagce643912015-05-06 06:33:17 +03002789 >>> from test.support import script_helper, temp_dir
2790 >>> with temp_dir() as tmpdir:
R David Murray5707d502013-06-23 14:24:13 -04002791 ... fn = os.path.join(tmpdir, 'myfile.doc')
2792 ... with open(fn, 'w') as f:
2793 ... _ = f.write('This is another simple test file.\n')
2794 ... _ = f.write(' >>> 1 + 1\n')
2795 ... _ = f.write(' 2\n')
2796 ... _ = f.write(' >>> "abcdef"\n')
2797 ... _ = f.write(" 'a...f'\n")
2798 ... _ = f.write(' >>> "ajkml"\n')
2799 ... _ = f.write(" 'a...l'\n")
2800 ... _ = f.write('\n')
2801 ... _ = f.write('And that is it.\n')
2802 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2803 ... with open(fn2, 'w') as f:
2804 ... _ = f.write('def test_func():\n')
2805 ... _ = f.write(' \"\"\"\n')
2806 ... _ = f.write(' This is simple python test function.\n')
2807 ... _ = f.write(' >>> 1 + 1\n')
2808 ... _ = f.write(' 2\n')
2809 ... _ = f.write(' >>> "abc def"\n')
2810 ... _ = f.write(" 'abc def'\n")
2811 ... _ = f.write("\n")
2812 ... _ = f.write(' \"\"\"\n')
R David Murray5707d502013-06-23 14:24:13 -04002813 ... rc1, out1, err1 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002814 ... '-m', 'doctest', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002815 ... rc2, out2, err2 = script_helper.assert_python_ok(
Berker Peksage4956462016-06-24 09:28:50 +03002816 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
R David Murray5707d502013-06-23 14:24:13 -04002817 ... rc3, out3, err3 = script_helper.assert_python_ok(
2818 ... '-m', 'doctest', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002819 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002820 ... rc4, out4, err4 = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002821 ... '-m', 'doctest', '-f', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002822 ... rc5, out5, err5 = script_helper.assert_python_ok(
2823 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
Berker Peksage4956462016-06-24 09:28:50 +03002824 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
R David Murray5707d502013-06-23 14:24:13 -04002825
2826Our first test run will show the errors from the first file (doctest stops if a
2827file has errors). Note that doctest test-run error output appears on stdout,
2828not stderr:
2829
2830 >>> rc1, err1
2831 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002832 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002833 **********************************************************************
2834 File "...myfile.doc", line 4, in myfile.doc
2835 Failed example:
2836 "abcdef"
2837 Expected:
2838 'a...f'
2839 Got:
2840 'abcdef'
2841 **********************************************************************
2842 File "...myfile.doc", line 6, in myfile.doc
2843 Failed example:
2844 "ajkml"
2845 Expected:
2846 'a...l'
2847 Got:
2848 'ajkml'
2849 **********************************************************************
2850 1 items had failures:
2851 2 of 3 in myfile.doc
2852 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002853
2854With -o ELLIPSIS specified, the second run, against just the first file, should
2855produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2856should the third, which ran against both files:
2857
2858 >>> rc2, out2, err2
2859 (0, b'', b'')
2860 >>> rc3, out3, err3
2861 (0, b'', b'')
2862
2863The fourth run uses FAIL_FAST, so we should see only one error:
2864
2865 >>> rc4, err4
2866 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002867 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002868 **********************************************************************
2869 File "...myfile.doc", line 4, in myfile.doc
2870 Failed example:
2871 "abcdef"
2872 Expected:
2873 'a...f'
2874 Got:
2875 'abcdef'
2876 **********************************************************************
2877 1 items had failures:
2878 1 of 2 in myfile.doc
2879 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002880
2881The fifth test uses verbose with the two options, so we should get verbose
2882success output for the tests in both files:
2883
2884 >>> rc5, err5
2885 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002886 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002887 Trying:
2888 1 + 1
2889 Expecting:
2890 2
2891 ok
2892 Trying:
2893 "abcdef"
2894 Expecting:
2895 'a...f'
2896 ok
2897 Trying:
2898 "ajkml"
2899 Expecting:
2900 'a...l'
2901 ok
2902 1 items passed all tests:
2903 3 tests in myfile.doc
2904 3 tests in 1 items.
2905 3 passed and 0 failed.
2906 Test passed.
2907 Trying:
2908 1 + 1
2909 Expecting:
2910 2
2911 ok
2912 Trying:
2913 "abc def"
2914 Expecting:
2915 'abc def'
2916 ok
2917 1 items had no tests:
2918 myfile2
2919 1 items passed all tests:
2920 2 tests in myfile2.test_func
2921 2 tests in 2 items.
2922 2 passed and 0 failed.
2923 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002924
2925We should also check some typical error cases.
2926
2927Invalid file name:
2928
2929 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002930 ... '-m', 'doctest', 'nosuchfile')
R David Murray5707d502013-06-23 14:24:13 -04002931 >>> rc, out
2932 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002933 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002934 Traceback (most recent call last):
2935 ...
2936 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
2937
2938Invalid doctest option:
2939
2940 >>> rc, out, err = script_helper.assert_python_failure(
Berker Peksage4956462016-06-24 09:28:50 +03002941 ... '-m', 'doctest', '-o', 'nosuchoption')
R David Murray5707d502013-06-23 14:24:13 -04002942 >>> rc, out
2943 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04002944 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002945 usage...invalid...nosuchoption...
2946
2947"""
2948
Tim Peters8485b562004-08-04 18:46:34 +00002949######################################################################
2950## Main
2951######################################################################
2952
2953def test_main():
2954 # Check the doctest cases in doctest itself:
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02002955 ret = support.run_doctest(doctest, verbosity=True)
Victor Stinner931602a2016-03-25 12:48:17 +01002956
Tim Peters8485b562004-08-04 18:46:34 +00002957 # Check the doctest cases defined here:
2958 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002959 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002960
Miss Islington (bot)5a0c3982018-03-06 07:16:11 -08002961 # Run unittests
2962 support.run_unittest(__name__)
2963
2964
Tim Peters8485b562004-08-04 18:46:34 +00002965def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002966 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01002967 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00002968 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002969 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002970 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002971 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002972 r.write_results(show_missing=True, summary=True,
2973 coverdir=coverdir)
2974
2975if __name__ == '__main__':
2976 if '-c' in sys.argv:
2977 test_coverage('/tmp/doctest.cover')
2978 else:
2979 test_main()