blob: 4b8d0d2b9c4596687c37c62d094bba5d59278fb1 [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
Victor Stinner9d396392010-10-16 21:54:59 +00007import os
Brett Cannon31f59292011-02-21 19:29:56 +00008import sys
Tim Peters8485b562004-08-04 18:46:34 +00009
Florent Xiclunadc6f2d02010-04-02 19:25:32 +000010
Nick Coghlanf088e5e2008-12-14 11:50:48 +000011# NOTE: There are some additional tests relating to interaction with
12# zipimport in the test_zipimport_support test module.
13
Tim Peters8485b562004-08-04 18:46:34 +000014######################################################################
15## Sample Objects (used by test cases)
16######################################################################
17
18def sample_func(v):
19 """
Tim Peters19397e52004-08-06 22:02:59 +000020 Blah blah
21
Guido van Rossum7131f842007-02-09 20:13:25 +000022 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000023 44
Tim Peters19397e52004-08-06 22:02:59 +000024
25 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000026 """
27 return v+v
28
29class SampleClass:
30 """
Guido van Rossum7131f842007-02-09 20:13:25 +000031 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000032 1
Edward Loper4ae900f2004-09-21 03:20:34 +000033
34 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
35 >>>
36 ...
37
38 Multiline example:
39 >>> sc = SampleClass(3)
40 >>> for i in range(10):
41 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000042 ... print(' ', sc.get(), sep='', end='')
43 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000044 """
45 def __init__(self, val):
46 """
Guido van Rossum7131f842007-02-09 20:13:25 +000047 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000048 12
49 """
50 self.val = val
51
52 def double(self):
53 """
Guido van Rossum7131f842007-02-09 20:13:25 +000054 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000055 24
56 """
57 return SampleClass(self.val + self.val)
58
59 def get(self):
60 """
Guido van Rossum7131f842007-02-09 20:13:25 +000061 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000062 -5
63 """
64 return self.val
65
66 def a_staticmethod(v):
67 """
Guido van Rossum7131f842007-02-09 20:13:25 +000068 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000069 11
70 """
71 return v+1
72 a_staticmethod = staticmethod(a_staticmethod)
73
74 def a_classmethod(cls, v):
75 """
Guido van Rossum7131f842007-02-09 20:13:25 +000076 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000077 12
Guido van Rossum7131f842007-02-09 20:13:25 +000078 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000079 12
80 """
81 return v+2
82 a_classmethod = classmethod(a_classmethod)
83
84 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000085 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000086 22
87 """)
88
89 class NestedClass:
90 """
91 >>> x = SampleClass.NestedClass(5)
92 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000093 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000094 25
95 """
96 def __init__(self, val=0):
97 """
Guido van Rossum7131f842007-02-09 20:13:25 +000098 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +000099 0
100 """
101 self.val = val
102 def square(self):
103 return SampleClass.NestedClass(self.val*self.val)
104 def get(self):
105 return self.val
106
107class SampleNewStyleClass(object):
108 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000109 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000110 1
111 2
112 3
113 """
114 def __init__(self, val):
115 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000116 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000117 12
118 """
119 self.val = val
120
121 def double(self):
122 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000123 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000124 24
125 """
126 return SampleNewStyleClass(self.val + self.val)
127
128 def get(self):
129 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000130 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000131 -5
132 """
133 return self.val
134
135######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000136## Fake stdin (for testing interactive debugging)
137######################################################################
138
139class _FakeInput:
140 """
141 A fake input stream for pdb's interactive debugger. Whenever a
142 line is read, print it (to simulate the user typing it), and then
143 return it. The set of lines to return is specified in the
144 constructor; they should not have trailing newlines.
145 """
146 def __init__(self, lines):
147 self.lines = lines
148
149 def readline(self):
150 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000151 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000152 return line+'\n'
153
154######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000155## Test Cases
156######################################################################
157
158def test_Example(): r"""
159Unit tests for the `Example` class.
160
Edward Lopera6b68322004-08-26 00:05:43 +0000161Example is a simple container class that holds:
162 - `source`: A source string.
163 - `want`: An expected output string.
164 - `exc_msg`: An expected exception message string (or None if no
165 exception is expected).
166 - `lineno`: A line number (within the docstring).
167 - `indent`: The example's indentation in the input string.
168 - `options`: An option dictionary, mapping option flags to True or
169 False.
Tim Peters8485b562004-08-04 18:46:34 +0000170
Edward Lopera6b68322004-08-26 00:05:43 +0000171These attributes are set by the constructor. `source` and `want` are
172required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000173
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000174 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000175 >>> (example.source, example.want, example.exc_msg,
176 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000177 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000178
179The first three attributes (`source`, `want`, and `exc_msg`) may be
180specified positionally; the remaining arguments should be specified as
181keyword arguments:
182
183 >>> exc_msg = 'IndexError: pop from an empty list'
184 >>> example = doctest.Example('[].pop()', '', exc_msg,
185 ... lineno=5, indent=4,
186 ... options={doctest.ELLIPSIS: True})
187 >>> (example.source, example.want, example.exc_msg,
188 ... example.lineno, example.indent, example.options)
189 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
190
191The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000192
Tim Petersbb431472004-08-09 03:51:46 +0000193 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000194 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000195 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000196 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000197
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000198 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000199 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000200 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000201
Tim Petersbb431472004-08-09 03:51:46 +0000202 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000203 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000204 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000205 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000206
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000207 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000208 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000209 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000210
Edward Lopera6b68322004-08-26 00:05:43 +0000211 Empty source string (which should never appear in real examples)
212 >>> e = doctest.Example('', '')
213 >>> e.source, e.want
214 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000215
Edward Lopera6b68322004-08-26 00:05:43 +0000216The constructor normalizes the `want` string to end in a newline,
217unless it's the empty string:
218
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000219 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000220 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000221 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000222
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000223 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000224 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000225 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000226
Edward Lopera6b68322004-08-26 00:05:43 +0000227 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000228 >>> e.source, e.want
229 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000230
231The constructor normalizes the `exc_msg` string to end in a newline,
232unless it's `None`:
233
234 Message spans one line
235 >>> exc_msg = 'IndexError: pop from an empty list'
236 >>> e = doctest.Example('[].pop()', '', exc_msg)
237 >>> e.exc_msg
238 'IndexError: pop from an empty list\n'
239
240 >>> exc_msg = 'IndexError: pop from an empty list\n'
241 >>> e = doctest.Example('[].pop()', '', exc_msg)
242 >>> e.exc_msg
243 'IndexError: pop from an empty list\n'
244
245 Message spans multiple lines
246 >>> exc_msg = 'ValueError: 1\n 2'
247 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
248 >>> e.exc_msg
249 'ValueError: 1\n 2\n'
250
251 >>> exc_msg = 'ValueError: 1\n 2\n'
252 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
253 >>> e.exc_msg
254 'ValueError: 1\n 2\n'
255
256 Empty (but non-None) exception message (which should never appear
257 in real examples)
258 >>> exc_msg = ''
259 >>> e = doctest.Example('raise X()', '', exc_msg)
260 >>> e.exc_msg
261 '\n'
Antoine Pitrou165b1282011-12-18 20:20:17 +0100262
263Compare `Example`:
264 >>> example = doctest.Example('print 1', '1\n')
265 >>> same_example = doctest.Example('print 1', '1\n')
266 >>> other_example = doctest.Example('print 42', '42\n')
267 >>> example == same_example
268 True
269 >>> example != same_example
270 False
271 >>> hash(example) == hash(same_example)
272 True
273 >>> example == other_example
274 False
275 >>> example != other_example
276 True
Tim Peters8485b562004-08-04 18:46:34 +0000277"""
278
279def test_DocTest(): r"""
280Unit tests for the `DocTest` class.
281
282DocTest is a collection of examples, extracted from a docstring, along
283with information about where the docstring comes from (a name,
284filename, and line number). The docstring is parsed by the `DocTest`
285constructor:
286
287 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000288 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000289 ... 12
290 ...
291 ... Non-example text.
292 ...
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000293 ... >>> print('another\example')
Tim Peters8485b562004-08-04 18:46:34 +0000294 ... another
295 ... example
296 ... '''
297 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000298 >>> parser = doctest.DocTestParser()
299 >>> test = parser.get_doctest(docstring, globs, 'some_test',
300 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000301 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000302 <DocTest some_test from some_file:20 (2 examples)>
303 >>> len(test.examples)
304 2
305 >>> e1, e2 = test.examples
306 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000307 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000308 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000309 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000310
311Source information (name, filename, and line number) is available as
312attributes on the doctest object:
313
314 >>> (test.name, test.filename, test.lineno)
315 ('some_test', 'some_file', 20)
316
317The line number of an example within its containing file is found by
318adding the line number of the example and the line number of its
319containing test:
320
321 >>> test.lineno + e1.lineno
322 21
323 >>> test.lineno + e2.lineno
324 26
325
326If the docstring contains inconsistant leading whitespace in the
327expected output of an example, then `DocTest` will raise a ValueError:
328
329 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000330 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000331 ... bad
332 ... indentation
333 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000334 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000335 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000336 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000337
338If the docstring contains inconsistent leading whitespace on
339continuation lines, then `DocTest` will raise a ValueError:
340
341 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000342 ... >>> print(('bad indentation',
343 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000344 ... ('bad', 'indentation')
345 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000346 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000347 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000348 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000349
350If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
351will raise a ValueError:
352
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000353 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000354 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000355 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000356 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000357
358If there's no blank space after a PS2 prompt ('...'), then `DocTest`
359will raise a ValueError:
360
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000361 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000362 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000363 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000364 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000365
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100366Compare `DocTest`:
367
368 >>> docstring = '''
369 ... >>> print 12
370 ... 12
371 ... '''
372 >>> test = parser.get_doctest(docstring, globs, 'some_test',
373 ... 'some_test', 20)
374 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
375 ... 'some_test', 20)
376 >>> test == same_test
377 True
378 >>> test != same_test
379 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100380 >>> hash(test) == hash(same_test)
381 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100382 >>> docstring = '''
383 ... >>> print 42
384 ... 42
385 ... '''
386 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
387 ... 'other_file', 10)
388 >>> test == other_test
389 False
390 >>> test != other_test
391 True
392
393Compare `DocTestCase`:
394
395 >>> DocTestCase = doctest.DocTestCase
396 >>> test_case = DocTestCase(test)
397 >>> same_test_case = DocTestCase(same_test)
398 >>> other_test_case = DocTestCase(other_test)
399 >>> test_case == same_test_case
400 True
401 >>> test_case != same_test_case
402 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100403 >>> hash(test_case) == hash(same_test_case)
404 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100405 >>> test == other_test_case
406 False
407 >>> test != other_test_case
408 True
409
Tim Peters8485b562004-08-04 18:46:34 +0000410"""
411
Zachary Ware7119b452013-11-24 02:21:57 -0600412class test_DocTestFinder:
413 def basics(): r"""
Tim Peters8485b562004-08-04 18:46:34 +0000414Unit tests for the `DocTestFinder` class.
415
416DocTestFinder is used to extract DocTests from an object's docstring
417and the docstrings of its contained objects. It can be used with
418modules, functions, classes, methods, staticmethods, classmethods, and
419properties.
420
421Finding Tests in Functions
422~~~~~~~~~~~~~~~~~~~~~~~~~~
423For a function whose docstring contains examples, DocTestFinder.find()
424will return a single test (for that function's docstring):
425
Tim Peters8485b562004-08-04 18:46:34 +0000426 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000427
428We'll simulate a __file__ attr that ends in pyc:
429
430 >>> import test.test_doctest
431 >>> old = test.test_doctest.__file__
432 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
433
Tim Peters8485b562004-08-04 18:46:34 +0000434 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000435
Guido van Rossum7131f842007-02-09 20:13:25 +0000436 >>> print(tests) # doctest: +ELLIPSIS
Brett Cannon31f59292011-02-21 19:29:56 +0000437 [<DocTest sample_func from ...:18 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000438
Tim Peters4de7c5c2004-08-23 22:38:05 +0000439The exact name depends on how test_doctest was invoked, so allow for
440leading path components.
441
442 >>> tests[0].filename # doctest: +ELLIPSIS
443 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000444
445 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000446
Jim Fulton07a349c2004-08-22 14:10:00 +0000447
Tim Peters8485b562004-08-04 18:46:34 +0000448 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000449 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000450 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000451
Edward Loper32ddbf72004-09-13 05:47:24 +0000452By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000453
454 >>> def no_docstring(v):
455 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000456 >>> finder.find(no_docstring)
457 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000458
459However, the optional argument `exclude_empty` to the DocTestFinder
460constructor can be used to exclude tests for objects with empty
461docstrings:
462
463 >>> def no_docstring(v):
464 ... pass
465 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
466 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000467 []
468
469If the function has a docstring with no examples, then a test with no
470examples is returned. (This lets `DocTestRunner` collect statistics
471about which functions have no tests -- but is that useful? And should
472an empty test also be created when there's no docstring?)
473
474 >>> def no_examples(v):
475 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000476 >>> finder.find(no_examples) # doctest: +ELLIPSIS
477 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000478
479Finding Tests in Classes
480~~~~~~~~~~~~~~~~~~~~~~~~
481For a class, DocTestFinder will create a test for the class's
482docstring, and will recursively explore its contents, including
483methods, classmethods, staticmethods, properties, and nested classes.
484
485 >>> finder = doctest.DocTestFinder()
486 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000487 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000488 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000489 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000490 3 SampleClass.NestedClass
491 1 SampleClass.NestedClass.__init__
492 1 SampleClass.__init__
493 2 SampleClass.a_classmethod
494 1 SampleClass.a_property
495 1 SampleClass.a_staticmethod
496 1 SampleClass.double
497 1 SampleClass.get
498
499New-style classes are also supported:
500
501 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000502 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000503 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000504 1 SampleNewStyleClass
505 1 SampleNewStyleClass.__init__
506 1 SampleNewStyleClass.double
507 1 SampleNewStyleClass.get
508
509Finding Tests in Modules
510~~~~~~~~~~~~~~~~~~~~~~~~
511For a module, DocTestFinder will create a test for the class's
512docstring, and will recursively explore its contents, including
513functions, classes, and the `__test__` dictionary, if it exists:
514
515 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000516 >>> import types
517 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000518 >>> def triple(val):
519 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000520 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000521 ... 33
522 ... '''
523 ... return val*3
524 >>> m.__dict__.update({
525 ... 'sample_func': sample_func,
526 ... 'SampleClass': SampleClass,
527 ... '__doc__': '''
528 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000529 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000530 ... module
531 ... ''',
532 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000533 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000534 ... 'c': triple}})
535
536 >>> finder = doctest.DocTestFinder()
537 >>> # Use module=test.test_doctest, to prevent doctest from
538 >>> # ignoring the objects since they weren't defined in m.
539 >>> import test.test_doctest
540 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000541 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000542 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000543 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000544 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000545 3 some_module.SampleClass.NestedClass
546 1 some_module.SampleClass.NestedClass.__init__
547 1 some_module.SampleClass.__init__
548 2 some_module.SampleClass.a_classmethod
549 1 some_module.SampleClass.a_property
550 1 some_module.SampleClass.a_staticmethod
551 1 some_module.SampleClass.double
552 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000553 1 some_module.__test__.c
554 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000555 1 some_module.sample_func
556
557Duplicate Removal
558~~~~~~~~~~~~~~~~~
559If a single object is listed twice (under different names), then tests
560will only be generated for it once:
561
Tim Petersf3f57472004-08-08 06:11:48 +0000562 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000563 >>> assert doctest_aliases.TwoNames.f
564 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000565 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000566 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000567 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000568 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000569 test.doctest_aliases.TwoNames
570
571 TwoNames.f and TwoNames.g are bound to the same object.
572 We can't guess which will be found in doctest's traversal of
573 TwoNames.__dict__ first, so we have to allow for either.
574
575 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000576 True
577
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000578Empty Tests
579~~~~~~~~~~~
580By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000581
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000582 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000583 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000584 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000585 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000586 3 SampleClass.NestedClass
587 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000588 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000589 2 SampleClass.a_classmethod
590 1 SampleClass.a_property
591 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000592 1 SampleClass.double
593 1 SampleClass.get
594
595By default, that excluded objects with no doctests. exclude_empty=False
596tells it to include (empty) tests for objects with no doctests. This feature
597is really to support backward compatibility in what doctest.master.summarize()
598displays.
599
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000600 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000601 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000602 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000603 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000604 3 SampleClass.NestedClass
605 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000606 0 SampleClass.NestedClass.get
607 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000608 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000609 2 SampleClass.a_classmethod
610 1 SampleClass.a_property
611 1 SampleClass.a_staticmethod
612 1 SampleClass.double
613 1 SampleClass.get
614
Tim Peters8485b562004-08-04 18:46:34 +0000615Turning off Recursion
616~~~~~~~~~~~~~~~~~~~~~
617DocTestFinder can be told not to look for tests in contained objects
618using the `recurse` flag:
619
620 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000621 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000622 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000623 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000624
625Line numbers
626~~~~~~~~~~~~
627DocTestFinder finds the line number of each example:
628
629 >>> def f(x):
630 ... '''
631 ... >>> x = 12
632 ...
633 ... some text
634 ...
635 ... >>> # examples are not created for comments & bare prompts.
636 ... >>>
637 ... ...
638 ...
639 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000640 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000641 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000642 ... >>> x//2
643 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000644 ... '''
645 >>> test = doctest.DocTestFinder().find(f)[0]
646 >>> [e.lineno for e in test.examples]
647 [1, 9, 12]
Zachary Ware7119b452013-11-24 02:21:57 -0600648"""
649
650 if int.__doc__: # simple check for --without-doc-strings, skip if lacking
651 def non_Python_modules(): r"""
Zachary Warea4b7a752013-11-24 01:19:09 -0600652
653Finding Doctests in Modules Not Written in Python
654~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
655DocTestFinder can also find doctests in most modules not written in Python.
656We'll use builtins as an example, since it almost certainly isn't written in
657plain ol' Python and is guaranteed to be available.
658
659 >>> import builtins
660 >>> tests = doctest.DocTestFinder().find(builtins)
Zachary Ware7119b452013-11-24 02:21:57 -0600661 >>> 790 < len(tests) < 800 # approximate number of objects with docstrings
662 True
Zachary Warea4b7a752013-11-24 01:19:09 -0600663 >>> real_tests = [t for t in tests if len(t.examples) > 0]
Zachary Ware7119b452013-11-24 02:21:57 -0600664 >>> len(real_tests) # objects that actually have doctests
Zachary Warea4b7a752013-11-24 01:19:09 -0600665 8
666 >>> for t in real_tests:
667 ... print('{} {}'.format(len(t.examples), t.name))
668 ...
669 1 builtins.bin
670 3 builtins.float.as_integer_ratio
671 2 builtins.float.fromhex
672 2 builtins.float.hex
673 1 builtins.hex
674 1 builtins.int
675 2 builtins.int.bit_length
676 1 builtins.oct
677
678Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
679'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
680and 'int' is a type.
Tim Peters8485b562004-08-04 18:46:34 +0000681"""
682
Edward Loper00f8da72004-08-26 18:05:07 +0000683def test_DocTestParser(): r"""
684Unit tests for the `DocTestParser` class.
685
686DocTestParser is used to parse docstrings containing doctest examples.
687
688The `parse` method divides a docstring into examples and intervening
689text:
690
691 >>> s = '''
692 ... >>> x, y = 2, 3 # no output expected
693 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000694 ... ... print(x)
695 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000696 ... 2
697 ... 3
698 ...
699 ... Some text.
700 ... >>> x+y
701 ... 5
702 ... '''
703 >>> parser = doctest.DocTestParser()
704 >>> for piece in parser.parse(s):
705 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000706 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000707 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000708 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000709 Text: '\n'
710 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
711 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000712 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000713 Text: '\nSome text.\n'
714 Example: ('x+y\n', '5\n', 9)
715 Text: ''
716
717The `get_examples` method returns just the examples:
718
719 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000720 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000721 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000722 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000723 ('x+y\n', '5\n', 9)
724
725The `get_doctest` method creates a Test from the examples, along with the
726given arguments:
727
728 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
729 >>> (test.name, test.filename, test.lineno)
730 ('name', 'filename', 5)
731 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000732 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000733 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000734 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000735 ('x+y\n', '5\n', 9)
736"""
737
Tim Peters8485b562004-08-04 18:46:34 +0000738class test_DocTestRunner:
739 def basics(): r"""
740Unit tests for the `DocTestRunner` class.
741
742DocTestRunner is used to run DocTest test cases, and to accumulate
743statistics. Here's a simple DocTest case we can use:
744
745 >>> def f(x):
746 ... '''
747 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000748 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000749 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000750 ... >>> x//2
751 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000752 ... '''
753 >>> test = doctest.DocTestFinder().find(f)[0]
754
755The main DocTestRunner interface is the `run` method, which runs a
756given DocTest case in a given namespace (globs). It returns a tuple
757`(f,t)`, where `f` is the number of failed tests and `t` is the number
758of tried tests.
759
760 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000761 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000762
763If any example produces incorrect output, then the test runner reports
764the failure and proceeds to the next example:
765
766 >>> def f(x):
767 ... '''
768 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000769 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000770 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000771 ... >>> x//2
772 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000773 ... '''
774 >>> test = doctest.DocTestFinder().find(f)[0]
775 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000776 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000777 Trying:
778 x = 12
779 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000780 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000781 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000782 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000783 Expecting:
784 14
Tim Peters8485b562004-08-04 18:46:34 +0000785 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000786 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000787 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000788 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000789 Expected:
790 14
791 Got:
792 12
Edward Loperaacf0832004-08-26 01:19:50 +0000793 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000794 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000795 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000796 6
Tim Peters8485b562004-08-04 18:46:34 +0000797 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000798 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000799"""
800 def verbose_flag(): r"""
801The `verbose` flag makes the test runner generate more detailed
802output:
803
804 >>> def f(x):
805 ... '''
806 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000807 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000808 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000809 ... >>> x//2
810 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000811 ... '''
812 >>> test = doctest.DocTestFinder().find(f)[0]
813
814 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000815 Trying:
816 x = 12
817 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000818 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000819 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000820 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000821 Expecting:
822 12
Tim Peters8485b562004-08-04 18:46:34 +0000823 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000824 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000825 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000826 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000827 6
Tim Peters8485b562004-08-04 18:46:34 +0000828 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000829 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000830
831If the `verbose` flag is unspecified, then the output will be verbose
832iff `-v` appears in sys.argv:
833
834 >>> # Save the real sys.argv list.
835 >>> old_argv = sys.argv
836
837 >>> # If -v does not appear in sys.argv, then output isn't verbose.
838 >>> sys.argv = ['test']
839 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000840 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000841
842 >>> # If -v does appear in sys.argv, then output is verbose.
843 >>> sys.argv = ['test', '-v']
844 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000845 Trying:
846 x = 12
847 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000848 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000849 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000850 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000851 Expecting:
852 12
Tim Peters8485b562004-08-04 18:46:34 +0000853 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000854 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000855 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000856 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000857 6
Tim Peters8485b562004-08-04 18:46:34 +0000858 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000859 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000860
861 >>> # Restore sys.argv
862 >>> sys.argv = old_argv
863
864In the remaining examples, the test runner's verbosity will be
865explicitly set, to ensure that the test behavior is consistent.
866 """
867 def exceptions(): r"""
868Tests of `DocTestRunner`'s exception handling.
869
870An expected exception is specified with a traceback message. The
871lines between the first line and the type/value may be omitted or
872replaced with any other string:
873
874 >>> def f(x):
875 ... '''
876 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000877 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000878 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000879 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000880 ... '''
881 >>> test = doctest.DocTestFinder().find(f)[0]
882 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000883 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000884
Edward Loper19b19582004-08-25 23:07:03 +0000885An example may not generate output before it raises an exception; if
886it does, then the traceback message will not be recognized as
887signaling an expected exception, so the example will be reported as an
888unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000889
890 >>> def f(x):
891 ... '''
892 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000893 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000894 ... pre-exception output
895 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000896 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000897 ... '''
898 >>> test = doctest.DocTestFinder().find(f)[0]
899 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000900 ... # doctest: +ELLIPSIS
901 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000902 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000903 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000904 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000905 Exception raised:
906 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000907 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000908 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000909
910Exception messages may contain newlines:
911
912 >>> def f(x):
913 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000914 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000915 ... Traceback (most recent call last):
916 ... ValueError: multi
917 ... line
918 ... message
919 ... '''
920 >>> test = doctest.DocTestFinder().find(f)[0]
921 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000922 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000923
924If an exception is expected, but an exception with the wrong type or
925message is raised, then it is reported as a failure:
926
927 >>> def f(x):
928 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000929 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000930 ... Traceback (most recent call last):
931 ... ValueError: wrong message
932 ... '''
933 >>> test = doctest.DocTestFinder().find(f)[0]
934 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000935 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000936 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000937 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000938 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000939 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000940 Expected:
941 Traceback (most recent call last):
942 ValueError: wrong message
943 Got:
944 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000945 ...
Tim Peters8485b562004-08-04 18:46:34 +0000946 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000947 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000948
Tim Peters1fbf9c52004-09-04 17:21:02 +0000949However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
950detail:
951
952 >>> def f(x):
953 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000954 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000955 ... Traceback (most recent call last):
956 ... ValueError: wrong message
957 ... '''
958 >>> test = doctest.DocTestFinder().find(f)[0]
959 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000960 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000961
Nick Coghlan5e76e942010-06-12 13:42:46 +0000962IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
963between Python versions. For example, in Python 2.x, the module path of
964the exception is not in the output, but this will fail under Python 3:
965
966 >>> def f(x):
967 ... r'''
968 ... >>> from http.client import HTTPException
969 ... >>> raise HTTPException('message')
970 ... Traceback (most recent call last):
971 ... HTTPException: message
972 ... '''
973 >>> test = doctest.DocTestFinder().find(f)[0]
974 >>> doctest.DocTestRunner(verbose=False).run(test)
975 ... # doctest: +ELLIPSIS
976 **********************************************************************
977 File ..., line 4, in f
978 Failed example:
979 raise HTTPException('message')
980 Expected:
981 Traceback (most recent call last):
982 HTTPException: message
983 Got:
984 Traceback (most recent call last):
985 ...
986 http.client.HTTPException: message
987 TestResults(failed=1, attempted=2)
988
989But in Python 3 the module path is included, and therefore a test must look
990like the following test to succeed in Python 3. But that test will fail under
991Python 2.
992
993 >>> def f(x):
994 ... r'''
995 ... >>> from http.client import HTTPException
996 ... >>> raise HTTPException('message')
997 ... Traceback (most recent call last):
998 ... http.client.HTTPException: message
999 ... '''
1000 >>> test = doctest.DocTestFinder().find(f)[0]
1001 >>> doctest.DocTestRunner(verbose=False).run(test)
1002 TestResults(failed=0, attempted=2)
1003
1004However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1005(or its unexpected absence) will be ignored:
1006
1007 >>> def f(x):
1008 ... r'''
1009 ... >>> from http.client import HTTPException
1010 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1011 ... Traceback (most recent call last):
1012 ... HTTPException: message
1013 ... '''
1014 >>> test = doctest.DocTestFinder().find(f)[0]
1015 >>> doctest.DocTestRunner(verbose=False).run(test)
1016 TestResults(failed=0, attempted=2)
1017
1018The module path will be completely ignored, so two different module paths will
1019still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1020be used when exceptions have changed module.
1021
1022 >>> def f(x):
1023 ... r'''
1024 ... >>> from http.client import HTTPException
1025 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1026 ... Traceback (most recent call last):
1027 ... foo.bar.HTTPException: message
1028 ... '''
1029 >>> test = doctest.DocTestFinder().find(f)[0]
1030 >>> doctest.DocTestRunner(verbose=False).run(test)
1031 TestResults(failed=0, attempted=2)
1032
Tim Peters1fbf9c52004-09-04 17:21:02 +00001033But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1034
1035 >>> def f(x):
1036 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001037 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001038 ... Traceback (most recent call last):
1039 ... TypeError: wrong type
1040 ... '''
1041 >>> test = doctest.DocTestFinder().find(f)[0]
1042 >>> doctest.DocTestRunner(verbose=False).run(test)
1043 ... # doctest: +ELLIPSIS
1044 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001045 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001046 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001047 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001048 Expected:
1049 Traceback (most recent call last):
1050 TypeError: wrong type
1051 Got:
1052 Traceback (most recent call last):
1053 ...
1054 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001055 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001056
Tim Petersf9a07f22013-12-03 21:02:05 -06001057If the exception does not have a message, you can still use
1058IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1059
1060 >>> def f(x):
1061 ... r'''
1062 ... >>> from http.client import HTTPException
1063 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1064 ... Traceback (most recent call last):
1065 ... foo.bar.HTTPException
1066 ... '''
1067 >>> test = doctest.DocTestFinder().find(f)[0]
1068 >>> doctest.DocTestRunner(verbose=False).run(test)
1069 TestResults(failed=0, attempted=2)
1070
1071Note that a trailing colon doesn't matter either:
1072
1073 >>> def f(x):
1074 ... r'''
1075 ... >>> from http.client import HTTPException
1076 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1077 ... Traceback (most recent call last):
1078 ... foo.bar.HTTPException:
1079 ... '''
1080 >>> test = doctest.DocTestFinder().find(f)[0]
1081 >>> doctest.DocTestRunner(verbose=False).run(test)
1082 TestResults(failed=0, attempted=2)
1083
Tim Peters8485b562004-08-04 18:46:34 +00001084If an exception is raised but not expected, then it is reported as an
1085unexpected exception:
1086
Tim Peters8485b562004-08-04 18:46:34 +00001087 >>> def f(x):
1088 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001089 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001090 ... 0
1091 ... '''
1092 >>> test = doctest.DocTestFinder().find(f)[0]
1093 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001094 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001095 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001096 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001097 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001098 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001099 Exception raised:
1100 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001101 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001102 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001103 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001104"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001105 def displayhook(): r"""
1106Test that changing sys.displayhook doesn't matter for doctest.
1107
1108 >>> import sys
1109 >>> orig_displayhook = sys.displayhook
1110 >>> def my_displayhook(x):
1111 ... print('hi!')
1112 >>> sys.displayhook = my_displayhook
1113 >>> def f():
1114 ... '''
1115 ... >>> 3
1116 ... 3
1117 ... '''
1118 >>> test = doctest.DocTestFinder().find(f)[0]
1119 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1120 >>> post_displayhook = sys.displayhook
1121
1122 We need to restore sys.displayhook now, so that we'll be able to test
1123 results.
1124
1125 >>> sys.displayhook = orig_displayhook
1126
1127 Ok, now we can check that everything is ok.
1128
1129 >>> r
1130 TestResults(failed=0, attempted=1)
1131 >>> post_displayhook is my_displayhook
1132 True
1133"""
Tim Peters8485b562004-08-04 18:46:34 +00001134 def optionflags(): r"""
1135Tests of `DocTestRunner`'s option flag handling.
1136
1137Several option flags can be used to customize the behavior of the test
1138runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001139to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001140together).
1141
1142The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1143and 1/0:
1144
1145 >>> def f(x):
1146 ... '>>> True\n1\n'
1147
1148 >>> # Without the flag:
1149 >>> test = doctest.DocTestFinder().find(f)[0]
1150 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001151 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001152
1153 >>> # With the flag:
1154 >>> test = doctest.DocTestFinder().find(f)[0]
1155 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1156 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001157 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001158 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001159 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001160 Failed example:
1161 True
1162 Expected:
1163 1
1164 Got:
1165 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001166 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001167
1168The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1169and the '<BLANKLINE>' marker:
1170
1171 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001172 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001173
1174 >>> # Without the flag:
1175 >>> test = doctest.DocTestFinder().find(f)[0]
1176 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001177 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001178
1179 >>> # With the flag:
1180 >>> test = doctest.DocTestFinder().find(f)[0]
1181 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1182 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001183 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001184 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001185 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001186 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001187 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001188 Expected:
1189 a
1190 <BLANKLINE>
1191 b
1192 Got:
1193 a
1194 <BLANKLINE>
1195 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001196 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001197
1198The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1199treated as equal:
1200
1201 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001202 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001203
1204 >>> # Without the flag:
1205 >>> test = doctest.DocTestFinder().find(f)[0]
1206 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001207 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001208 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001209 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001210 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001211 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001212 Expected:
1213 1 2
1214 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001215 Got:
1216 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001217 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001218
1219 >>> # With the flag:
1220 >>> test = doctest.DocTestFinder().find(f)[0]
1221 >>> flags = doctest.NORMALIZE_WHITESPACE
1222 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001223 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001224
Tim Peters026f8dc2004-08-19 16:38:58 +00001225 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001226 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001227 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1228 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1229
Tim Peters8485b562004-08-04 18:46:34 +00001230The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1231output to match any substring in the actual output:
1232
1233 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001234 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001235
1236 >>> # Without the flag:
1237 >>> test = doctest.DocTestFinder().find(f)[0]
1238 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001239 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001240 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001241 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001242 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001243 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001244 Expected:
1245 [0, 1, 2, ..., 14]
1246 Got:
1247 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001248 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001249
1250 >>> # With the flag:
1251 >>> test = doctest.DocTestFinder().find(f)[0]
1252 >>> flags = doctest.ELLIPSIS
1253 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001254 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001255
Tim Peterse594bee2004-08-22 01:47:51 +00001256 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001257
Guido van Rossume0192e52007-02-09 23:39:59 +00001258 >>> if 1:
1259 ... for i in range(100):
1260 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1261 ... print('!')
1262 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001263
Tim Peters026f8dc2004-08-19 16:38:58 +00001264 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001265
Guido van Rossume0192e52007-02-09 23:39:59 +00001266 >>> if 1: #doctest: +ELLIPSIS
1267 ... for i in range(20):
1268 ... print(i, end=' ')
1269 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001270 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001271
Tim Peters026f8dc2004-08-19 16:38:58 +00001272 Examples from the docs:
1273
Guido van Rossum805365e2007-05-07 22:24:25 +00001274 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001275 [0, 1, ..., 18, 19]
1276
Guido van Rossum805365e2007-05-07 22:24:25 +00001277 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001278 ... # doctest: +NORMALIZE_WHITESPACE
1279 [0, 1, ..., 18, 19]
1280
Thomas Wouters477c8d52006-05-27 19:21:47 +00001281The SKIP flag causes an example to be skipped entirely. I.e., the
1282example is not run. It can be useful in contexts where doctest
1283examples serve as both documentation and test cases, and an example
1284should be included for documentation purposes, but should not be
1285checked (e.g., because its output is random, or depends on resources
1286which would be unavailable.) The SKIP flag can also be used for
1287'commenting out' broken examples.
1288
1289 >>> import unavailable_resource # doctest: +SKIP
1290 >>> unavailable_resource.do_something() # doctest: +SKIP
1291 >>> unavailable_resource.blow_up() # doctest: +SKIP
1292 Traceback (most recent call last):
1293 ...
1294 UncheckedBlowUpError: Nobody checks me.
1295
1296 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001297 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001298 0.721216923889
1299
Edward Loper71f55af2004-08-26 01:41:51 +00001300The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001301and actual outputs to be displayed using a unified diff:
1302
1303 >>> def f(x):
1304 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001305 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001306 ... a
1307 ... B
1308 ... c
1309 ... d
1310 ... f
1311 ... g
1312 ... h
1313 ... '''
1314
1315 >>> # Without the flag:
1316 >>> test = doctest.DocTestFinder().find(f)[0]
1317 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001318 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001319 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001320 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001321 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001322 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001323 Expected:
1324 a
1325 B
1326 c
1327 d
1328 f
1329 g
1330 h
1331 Got:
1332 a
1333 b
1334 c
1335 d
1336 e
1337 f
1338 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001339 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001340
1341 >>> # With the flag:
1342 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001343 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001344 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001345 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001346 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001347 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001348 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001349 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001350 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001351 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001352 a
1353 -B
1354 +b
1355 c
1356 d
1357 +e
1358 f
1359 g
1360 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001361 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001362
Edward Loper71f55af2004-08-26 01:41:51 +00001363The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001364and actual outputs to be displayed using a context diff:
1365
Edward Loper71f55af2004-08-26 01:41:51 +00001366 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001367 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001368 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001369 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001370 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001371 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001372 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001373 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001374 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001375 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001376 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001377 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001378 a
1379 ! B
1380 c
1381 d
1382 f
1383 g
1384 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001385 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001386 a
1387 ! b
1388 c
1389 d
1390 + e
1391 f
1392 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001393 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001394
1395
Edward Loper71f55af2004-08-26 01:41:51 +00001396The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001397used by the popular ndiff.py utility. This does intraline difference
1398marking, as well as interline differences.
1399
1400 >>> def f(x):
1401 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001402 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001403 ... a b c d e f g h i j k 1 m
1404 ... '''
1405 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001406 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001407 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001408 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001409 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001410 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001411 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001412 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001413 Differences (ndiff with -expected +actual):
1414 - a b c d e f g h i j k 1 m
1415 ? ^
1416 + a b c d e f g h i j k l m
1417 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001418 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001419
Ezio Melotti13925002011-03-16 11:05:33 +02001420The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001421failing example:
1422
1423 >>> def f(x):
1424 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001425 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001426 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001427 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001428 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001429 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001430 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001431 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001432 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001433 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001434 ... 500
1435 ... '''
1436 >>> test = doctest.DocTestFinder().find(f)[0]
1437 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1438 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001439 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001440 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001441 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001442 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001443 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001444 Expected:
1445 200
1446 Got:
1447 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001448 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001449
Ezio Melotti13925002011-03-16 11:05:33 +02001450However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001451
1452 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001453 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001454 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001455 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001456 Expecting:
1457 1
1458 ok
1459 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001460 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001461 Expecting:
1462 200
1463 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001464 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001465 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001466 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001467 Expected:
1468 200
1469 Got:
1470 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001471 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001472
R David Murray5a9d7062012-11-21 15:09:21 -05001473The FAIL_FAST flag causes the runner to exit after the first failing example,
1474so subsequent examples are not even attempted:
1475
1476 >>> flags = doctest.FAIL_FAST
1477 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1478 ... # doctest: +ELLIPSIS
1479 **********************************************************************
1480 File ..., line 5, in f
1481 Failed example:
1482 print(2) # first failure
1483 Expected:
1484 200
1485 Got:
1486 2
1487 TestResults(failed=1, attempted=2)
1488
1489Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1490FAIL_FAST only:
1491
1492 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1493 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1494 ... # doctest: +ELLIPSIS
1495 **********************************************************************
1496 File ..., line 5, in f
1497 Failed example:
1498 print(2) # first failure
1499 Expected:
1500 200
1501 Got:
1502 2
1503 TestResults(failed=1, attempted=2)
1504
1505For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1506exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001507
1508 >>> def f(x):
1509 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001510 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001511 ... 1
1512 ... >>> raise ValueError(2) # first failure
1513 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001514 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001515 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001516 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001517 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001518 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001519 ... 500
1520 ... '''
1521 >>> test = doctest.DocTestFinder().find(f)[0]
1522 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1523 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1524 ... # doctest: +ELLIPSIS
1525 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001526 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001527 Failed example:
1528 raise ValueError(2) # first failure
1529 Exception raised:
1530 ...
1531 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001532 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001533 >>> flags = doctest.FAIL_FAST
1534 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1535 ... # doctest: +ELLIPSIS
1536 **********************************************************************
1537 File ..., line 5, in f
1538 Failed example:
1539 raise ValueError(2) # first failure
1540 Exception raised:
1541 ...
1542 ValueError: 2
1543 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001544
Thomas Wouters477c8d52006-05-27 19:21:47 +00001545New option flags can also be registered, via register_optionflag(). Here
1546we reach into doctest's internals a bit.
1547
1548 >>> unlikely = "UNLIKELY_OPTION_NAME"
1549 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1550 False
1551 >>> new_flag_value = doctest.register_optionflag(unlikely)
1552 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1553 True
1554
1555Before 2.4.4/2.5, registering a name more than once erroneously created
1556more than one flag value. Here we verify that's fixed:
1557
1558 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1559 >>> redundant_flag_value == new_flag_value
1560 True
1561
1562Clean up.
1563 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1564
Tim Petersc6cbab02004-08-22 19:43:28 +00001565 """
1566
Tim Peters8485b562004-08-04 18:46:34 +00001567 def option_directives(): r"""
1568Tests of `DocTestRunner`'s option directive mechanism.
1569
Edward Loper74bca7a2004-08-12 02:27:44 +00001570Option directives can be used to turn option flags on or off for a
1571single example. To turn an option on for an example, follow that
1572example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001573
1574 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001575 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001576 ... [0, 1, ..., 9]
1577 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001578 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001579 ... [0, 1, ..., 9]
1580 ... '''
1581 >>> test = doctest.DocTestFinder().find(f)[0]
1582 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001583 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001584 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001585 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001586 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001587 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001588 Expected:
1589 [0, 1, ..., 9]
1590 Got:
1591 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001592 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001593
1594To turn an option off for an example, follow that example with a
1595comment of the form ``# doctest: -OPTION``:
1596
1597 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001598 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001599 ... [0, 1, ..., 9]
1600 ...
1601 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001602 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001603 ... [0, 1, ..., 9]
1604 ... '''
1605 >>> test = doctest.DocTestFinder().find(f)[0]
1606 >>> doctest.DocTestRunner(verbose=False,
1607 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001608 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001609 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001610 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001611 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001612 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001613 Expected:
1614 [0, 1, ..., 9]
1615 Got:
1616 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001617 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001618
1619Option directives affect only the example that they appear with; they
1620do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001621
Edward Loper74bca7a2004-08-12 02:27:44 +00001622 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001623 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001624 ... [0, 1, ..., 9]
1625 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001626 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001627 ... [0, 1, ..., 9]
1628 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001629 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001630 ... [0, 1, ..., 9]
1631 ... '''
1632 >>> test = doctest.DocTestFinder().find(f)[0]
1633 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001634 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001635 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001636 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001637 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001638 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001639 Expected:
1640 [0, 1, ..., 9]
1641 Got:
1642 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001643 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001644 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001645 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001646 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001647 Expected:
1648 [0, 1, ..., 9]
1649 Got:
1650 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001651 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001652
Edward Loper74bca7a2004-08-12 02:27:44 +00001653Multiple options may be modified by a single option directive. They
1654may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001655
1656 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001657 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001658 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001659 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001660 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001661 ... [0, 1, ..., 9]
1662 ... '''
1663 >>> test = doctest.DocTestFinder().find(f)[0]
1664 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001665 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001666 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001667 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001668 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001669 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001670 Expected:
1671 [0, 1, ..., 9]
1672 Got:
1673 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001674 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001675
1676 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001677 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001678 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001679 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001680 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1681 ... [0, 1, ..., 9]
1682 ... '''
1683 >>> test = doctest.DocTestFinder().find(f)[0]
1684 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001685 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001686 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001687 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001688 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001689 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001690 Expected:
1691 [0, 1, ..., 9]
1692 Got:
1693 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001694 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001695
1696 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001697 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001698 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001699 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001700 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1701 ... [0, 1, ..., 9]
1702 ... '''
1703 >>> test = doctest.DocTestFinder().find(f)[0]
1704 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001705 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001706 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001707 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001708 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001709 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001710 Expected:
1711 [0, 1, ..., 9]
1712 Got:
1713 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001714 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001715
1716The option directive may be put on the line following the source, as
1717long as a continuation prompt is used:
1718
1719 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001720 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001721 ... ... # doctest: +ELLIPSIS
1722 ... [0, 1, ..., 9]
1723 ... '''
1724 >>> test = doctest.DocTestFinder().find(f)[0]
1725 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001726 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001727
Edward Loper74bca7a2004-08-12 02:27:44 +00001728For examples with multi-line source, the option directive may appear
1729at the end of any line:
1730
1731 >>> def f(x): r'''
1732 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001733 ... ... print(' ', x, end='', sep='')
1734 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001735 ...
1736 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001737 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1738 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001739 ... '''
1740 >>> test = doctest.DocTestFinder().find(f)[0]
1741 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001742 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001743
1744If more than one line of an example with multi-line source has an
1745option directive, then they are combined:
1746
1747 >>> def f(x): r'''
1748 ... Should fail (option directive not on the last line):
1749 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001750 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001751 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001752 ... '''
1753 >>> test = doctest.DocTestFinder().find(f)[0]
1754 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001755 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001756
1757It is an error to have a comment of the form ``# doctest:`` that is
1758*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1759``OPTION`` is an option that has been registered with
1760`register_option`:
1761
1762 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001763 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001764 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1765 Traceback (most recent call last):
1766 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1767
1768 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001769 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001770 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1771 Traceback (most recent call last):
1772 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1773
1774It is an error to use an option directive on a line that contains no
1775source:
1776
1777 >>> s = '>>> # doctest: +ELLIPSIS'
1778 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1779 Traceback (most recent call last):
1780 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 +00001781"""
1782
1783def test_testsource(): r"""
1784Unit tests for `testsource()`.
1785
1786The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001787test with that name in that module, and converts it to a script. The
1788example code is converted to regular Python code. The surrounding
1789words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001790
1791 >>> import test.test_doctest
1792 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001793 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001794 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001795 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001796 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001797 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001798 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001799 #
Edward Lopera5db6002004-08-12 02:41:30 +00001800 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001801 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001802
1803 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001804 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001805 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001806 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001807 ## 1
1808 ## 2
1809 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001810 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001811
1812 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001813 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001814 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001815 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001816 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001817 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001818 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001819 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001820 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001821"""
1822
1823def test_debug(): r"""
1824
1825Create a docstring that we want to debug:
1826
1827 >>> s = '''
1828 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001829 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001830 ... 12
1831 ... '''
1832
1833Create some fake stdin input, to feed to the debugger:
1834
Tim Peters8485b562004-08-04 18:46:34 +00001835 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001836 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001837
1838Run the debugger on the docstring, and then restore sys.stdin.
1839
Edward Loper2de91ba2004-08-27 02:07:46 +00001840 >>> try: doctest.debug_src(s)
1841 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001843 (Pdb) next
1844 12
Tim Peters8485b562004-08-04 18:46:34 +00001845 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001847 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001848 12
1849 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001850
1851"""
1852
Brett Cannon31f59292011-02-21 19:29:56 +00001853if not hasattr(sys, 'gettrace') or not sys.gettrace():
1854 def test_pdb_set_trace():
1855 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001856
Brett Cannon31f59292011-02-21 19:29:56 +00001857 You can use pdb.set_trace from a doctest. To do so, you must
1858 retrieve the set_trace function from the pdb module at the time
1859 you use it. The doctest module changes sys.stdout so that it can
1860 capture program output. It also temporarily replaces pdb.set_trace
1861 with a version that restores stdout. This is necessary for you to
1862 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001863
Brett Cannon31f59292011-02-21 19:29:56 +00001864 >>> doc = '''
1865 ... >>> x = 42
1866 ... >>> raise Exception('clé')
1867 ... Traceback (most recent call last):
1868 ... Exception: clé
1869 ... >>> import pdb; pdb.set_trace()
1870 ... '''
1871 >>> parser = doctest.DocTestParser()
1872 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1873 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001874
Brett Cannon31f59292011-02-21 19:29:56 +00001875 To demonstrate this, we'll create a fake standard input that
1876 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001877
Brett Cannon31f59292011-02-21 19:29:56 +00001878 >>> import tempfile
1879 >>> real_stdin = sys.stdin
1880 >>> sys.stdin = _FakeInput([
1881 ... 'print(x)', # print data defined by the example
1882 ... 'continue', # stop debugging
1883 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001884
Brett Cannon31f59292011-02-21 19:29:56 +00001885 >>> try: runner.run(test)
1886 ... finally: sys.stdin = real_stdin
1887 --Return--
1888 > <doctest foo-bar@baz[2]>(1)<module>()->None
1889 -> import pdb; pdb.set_trace()
1890 (Pdb) print(x)
1891 42
1892 (Pdb) continue
1893 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001894
Brett Cannon31f59292011-02-21 19:29:56 +00001895 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001896
Brett Cannon31f59292011-02-21 19:29:56 +00001897 >>> def calls_set_trace():
1898 ... y=2
1899 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001900
Brett Cannon31f59292011-02-21 19:29:56 +00001901 >>> doc = '''
1902 ... >>> x=1
1903 ... >>> calls_set_trace()
1904 ... '''
1905 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1906 >>> real_stdin = sys.stdin
1907 >>> sys.stdin = _FakeInput([
1908 ... 'print(y)', # print data defined in the function
1909 ... 'up', # out of function
1910 ... 'print(x)', # print data defined by the example
1911 ... 'continue', # stop debugging
1912 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001913
Brett Cannon31f59292011-02-21 19:29:56 +00001914 >>> try:
1915 ... runner.run(test)
1916 ... finally:
1917 ... sys.stdin = real_stdin
1918 --Return--
1919 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1920 -> import pdb; pdb.set_trace()
1921 (Pdb) print(y)
1922 2
1923 (Pdb) up
1924 > <doctest foo-bar@baz[1]>(1)<module>()
1925 -> calls_set_trace()
1926 (Pdb) print(x)
1927 1
1928 (Pdb) continue
1929 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001930
Brett Cannon31f59292011-02-21 19:29:56 +00001931 During interactive debugging, source code is shown, even for
1932 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001933
Brett Cannon31f59292011-02-21 19:29:56 +00001934 >>> doc = '''
1935 ... >>> def f(x):
1936 ... ... g(x*2)
1937 ... >>> def g(x):
1938 ... ... print(x+3)
1939 ... ... import pdb; pdb.set_trace()
1940 ... >>> f(3)
1941 ... '''
1942 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1943 >>> real_stdin = sys.stdin
1944 >>> sys.stdin = _FakeInput([
1945 ... 'list', # list source from example 2
1946 ... 'next', # return from g()
1947 ... 'list', # list source from example 1
1948 ... 'next', # return from f()
1949 ... 'list', # list source from example 3
1950 ... 'continue', # stop debugging
1951 ... ''])
1952 >>> try: runner.run(test)
1953 ... finally: sys.stdin = real_stdin
1954 ... # doctest: +NORMALIZE_WHITESPACE
1955 --Return--
1956 > <doctest foo-bar@baz[1]>(3)g()->None
1957 -> import pdb; pdb.set_trace()
1958 (Pdb) list
1959 1 def g(x):
1960 2 print(x+3)
1961 3 -> import pdb; pdb.set_trace()
1962 [EOF]
1963 (Pdb) next
1964 --Return--
1965 > <doctest foo-bar@baz[0]>(2)f()->None
1966 -> g(x*2)
1967 (Pdb) list
1968 1 def f(x):
1969 2 -> g(x*2)
1970 [EOF]
1971 (Pdb) next
1972 --Return--
1973 > <doctest foo-bar@baz[2]>(1)<module>()->None
1974 -> f(3)
1975 (Pdb) list
1976 1 -> f(3)
1977 [EOF]
1978 (Pdb) continue
1979 **********************************************************************
1980 File "foo-bar@baz.py", line 7, in foo-bar@baz
1981 Failed example:
1982 f(3)
1983 Expected nothing
1984 Got:
1985 9
1986 TestResults(failed=1, attempted=3)
1987 """
Jim Fulton356fd192004-08-09 11:34:47 +00001988
Brett Cannon31f59292011-02-21 19:29:56 +00001989 def test_pdb_set_trace_nested():
1990 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00001991
Brett Cannon31f59292011-02-21 19:29:56 +00001992 >>> class C(object):
1993 ... def calls_set_trace(self):
1994 ... y = 1
1995 ... import pdb; pdb.set_trace()
1996 ... self.f1()
1997 ... y = 2
1998 ... def f1(self):
1999 ... x = 1
2000 ... self.f2()
2001 ... x = 2
2002 ... def f2(self):
2003 ... z = 1
2004 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00002005
Brett Cannon31f59292011-02-21 19:29:56 +00002006 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00002007
Brett Cannon31f59292011-02-21 19:29:56 +00002008 >>> doc = '''
2009 ... >>> a = 1
2010 ... >>> calls_set_trace()
2011 ... '''
2012 >>> parser = doctest.DocTestParser()
2013 >>> runner = doctest.DocTestRunner(verbose=False)
2014 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
2015 >>> real_stdin = sys.stdin
2016 >>> sys.stdin = _FakeInput([
2017 ... 'print(y)', # print data defined in the function
2018 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2019 ... 'up', 'print(x)',
2020 ... 'up', 'print(y)',
2021 ... 'up', 'print(foo)',
2022 ... 'continue', # stop debugging
2023 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00002024
Brett Cannon31f59292011-02-21 19:29:56 +00002025 >>> try:
2026 ... runner.run(test)
2027 ... finally:
2028 ... sys.stdin = real_stdin
2029 ... # doctest: +REPORT_NDIFF
2030 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2031 -> self.f1()
2032 (Pdb) print(y)
2033 1
2034 (Pdb) step
2035 --Call--
2036 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2037 -> def f1(self):
2038 (Pdb) step
2039 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2040 -> x = 1
2041 (Pdb) step
2042 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2043 -> self.f2()
2044 (Pdb) step
2045 --Call--
2046 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2047 -> def f2(self):
2048 (Pdb) step
2049 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2050 -> z = 1
2051 (Pdb) step
2052 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2053 -> z = 2
2054 (Pdb) print(z)
2055 1
2056 (Pdb) up
2057 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2058 -> self.f2()
2059 (Pdb) print(x)
2060 1
2061 (Pdb) up
2062 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2063 -> self.f1()
2064 (Pdb) print(y)
2065 1
2066 (Pdb) up
2067 > <doctest foo-bar@baz[1]>(1)<module>()
2068 -> calls_set_trace()
2069 (Pdb) print(foo)
2070 *** NameError: name 'foo' is not defined
2071 (Pdb) continue
2072 TestResults(failed=0, attempted=2)
2073 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002074
Tim Peters19397e52004-08-06 22:02:59 +00002075def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002076 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002077
2078 We create a Suite by providing a module. A module can be provided
2079 by passing a module object:
2080
2081 >>> import unittest
2082 >>> import test.sample_doctest
2083 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2084 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002085 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002086
2087 We can also supply the module by name:
2088
2089 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2090 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002091 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002092
R David Murray5abd76a2012-09-10 10:15:58 -04002093 The module need not contain any doctest examples:
2094
2095 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2096 >>> suite.run(unittest.TestResult())
2097 <unittest.result.TestResult run=0 errors=0 failures=0>
2098
R David Murray1976d9b2014-04-14 20:28:36 -04002099 The module need not contain any docstrings either:
R David Murray5abd76a2012-09-10 10:15:58 -04002100
R David Murray1976d9b2014-04-14 20:28:36 -04002101 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
R David Murray5abd76a2012-09-10 10:15:58 -04002102 >>> suite.run(unittest.TestResult())
2103 <unittest.result.TestResult run=0 errors=0 failures=0>
2104
Tim Peters19397e52004-08-06 22:02:59 +00002105 We can use the current module:
2106
2107 >>> suite = test.sample_doctest.test_suite()
2108 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002109 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002110
R David Murray1976d9b2014-04-14 20:28:36 -04002111 We can also provide a DocTestFinder:
2112
2113 >>> finder = doctest.DocTestFinder()
2114 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2115 ... test_finder=finder)
2116 >>> suite.run(unittest.TestResult())
2117 <unittest.result.TestResult run=9 errors=0 failures=4>
2118
2119 The DocTestFinder need not return any tests:
2120
2121 >>> finder = doctest.DocTestFinder()
2122 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2123 ... test_finder=finder)
2124 >>> suite.run(unittest.TestResult())
2125 <unittest.result.TestResult run=0 errors=0 failures=0>
2126
Tim Peters19397e52004-08-06 22:02:59 +00002127 We can supply global variables. If we pass globs, they will be
2128 used instead of the module globals. Here we'll pass an empty
2129 globals, triggering an extra error:
2130
2131 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2132 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002133 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002134
2135 Alternatively, we can provide extra globals. Here we'll make an
2136 error go away by providing an extra global variable:
2137
2138 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2139 ... extraglobs={'y': 1})
2140 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002141 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002142
2143 You can pass option flags. Here we'll cause an extra error
2144 by disabling the blank-line feature:
2145
2146 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002147 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002148 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002149 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002150
Tim Peters1e277ee2004-08-07 05:37:52 +00002151 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002152
Jim Fultonf54bad42004-08-28 14:57:56 +00002153 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002154 ... import test.test_doctest
2155 ... test.test_doctest.sillySetup = True
2156
Jim Fultonf54bad42004-08-28 14:57:56 +00002157 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002158 ... import test.test_doctest
2159 ... del test.test_doctest.sillySetup
2160
2161 Here, we installed a silly variable that the test expects:
2162
2163 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2164 ... setUp=setUp, tearDown=tearDown)
2165 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002166 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002167
2168 But the tearDown restores sanity:
2169
2170 >>> import test.test_doctest
2171 >>> test.test_doctest.sillySetup
2172 Traceback (most recent call last):
2173 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002174 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002175
Jim Fultonf54bad42004-08-28 14:57:56 +00002176 The setUp and tearDown funtions are passed test objects. Here
2177 we'll use the setUp function to supply the missing variable y:
2178
2179 >>> def setUp(test):
2180 ... test.globs['y'] = 1
2181
2182 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2183 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002184 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002185
2186 Here, we didn't need to use a tearDown function because we
2187 modified the test globals, which are a copy of the
2188 sample_doctest module dictionary. The test globals are
2189 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002190 """
2191
2192def test_DocFileSuite():
2193 """We can test tests found in text files using a DocFileSuite.
2194
2195 We create a suite by providing the names of one or more text
2196 files that include examples:
2197
2198 >>> import unittest
2199 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002200 ... 'test_doctest2.txt',
2201 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002202 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002203 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002204
2205 The test files are looked for in the directory containing the
2206 calling module. A package keyword argument can be provided to
2207 specify a different relative location.
2208
2209 >>> import unittest
2210 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2211 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002212 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002213 ... package='test')
2214 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002215 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002216
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002217 Support for using a package's __loader__.get_data() is also
2218 provided.
2219
2220 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002221 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002222 >>> if not hasattr(test, '__loader__'):
2223 ... test.__loader__ = pkgutil.get_loader(test)
2224 ... added_loader = True
2225 >>> try:
2226 ... suite = doctest.DocFileSuite('test_doctest.txt',
2227 ... 'test_doctest2.txt',
2228 ... 'test_doctest4.txt',
2229 ... package='test')
2230 ... suite.run(unittest.TestResult())
2231 ... finally:
2232 ... if added_loader:
2233 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002234 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002235
Edward Loper0273f5b2004-09-18 20:27:04 +00002236 '/' should be used as a path separator. It will be converted
2237 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002238
2239 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2240 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002241 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002242
Edward Loper0273f5b2004-09-18 20:27:04 +00002243 If DocFileSuite is used from an interactive session, then files
2244 are resolved relative to the directory of sys.argv[0]:
2245
Christian Heimes45f9af32007-11-27 21:50:00 +00002246 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002247 >>> save_argv = sys.argv
2248 >>> sys.argv = [test.test_doctest.__file__]
2249 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002250 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002251 >>> sys.argv = save_argv
2252
Edward Loper052d0cd2004-09-19 17:19:33 +00002253 By setting `module_relative=False`, os-specific paths may be
2254 used (including absolute paths and paths relative to the
2255 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002256
2257 >>> # Get the absolute path of the test package.
2258 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2259 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2260
2261 >>> # Use it to find the absolute path of test_doctest.txt.
2262 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2263
Edward Loper052d0cd2004-09-19 17:19:33 +00002264 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002265 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002266 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002267
Edward Loper052d0cd2004-09-19 17:19:33 +00002268 It is an error to specify `package` when `module_relative=False`:
2269
2270 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2271 ... package='test')
2272 Traceback (most recent call last):
2273 ValueError: Package may only be specified for module-relative paths.
2274
Tim Peters19397e52004-08-06 22:02:59 +00002275 You can specify initial global variables:
2276
2277 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2278 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002279 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002280 ... globs={'favorite_color': 'blue'})
2281 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002282 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002283
2284 In this case, we supplied a missing favorite color. You can
2285 provide doctest options:
2286
2287 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2288 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002289 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002290 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2291 ... globs={'favorite_color': 'blue'})
2292 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002293 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002294
2295 And, you can provide setUp and tearDown functions:
2296
Jim Fultonf54bad42004-08-28 14:57:56 +00002297 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002298 ... import test.test_doctest
2299 ... test.test_doctest.sillySetup = True
2300
Jim Fultonf54bad42004-08-28 14:57:56 +00002301 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002302 ... import test.test_doctest
2303 ... del test.test_doctest.sillySetup
2304
2305 Here, we installed a silly variable that the test expects:
2306
2307 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2308 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002309 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002310 ... setUp=setUp, tearDown=tearDown)
2311 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002312 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002313
2314 But the tearDown restores sanity:
2315
2316 >>> import test.test_doctest
2317 >>> test.test_doctest.sillySetup
2318 Traceback (most recent call last):
2319 ...
Ethan Furman7b9ff0e2014-04-24 14:47:47 -07002320 AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
Tim Peters19397e52004-08-06 22:02:59 +00002321
Jim Fultonf54bad42004-08-28 14:57:56 +00002322 The setUp and tearDown funtions are passed test objects.
2323 Here, we'll use a setUp function to set the favorite color in
2324 test_doctest.txt:
2325
2326 >>> def setUp(test):
2327 ... test.globs['favorite_color'] = 'blue'
2328
2329 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2330 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002331 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002332
2333 Here, we didn't need to use a tearDown function because we
2334 modified the test globals. The test globals are
2335 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002336
Fred Drake7c404a42004-12-21 23:46:34 +00002337 Tests in a file run using `DocFileSuite` can also access the
2338 `__file__` global, which is set to the name of the file
2339 containing the tests:
2340
2341 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2342 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002343 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002344
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002345 If the tests contain non-ASCII characters, we have to specify which
2346 encoding the file is encoded with. We do so by using the `encoding`
2347 parameter:
2348
2349 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2350 ... 'test_doctest2.txt',
2351 ... 'test_doctest4.txt',
2352 ... encoding='utf-8')
2353 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002354 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002355
Jim Fultonf54bad42004-08-28 14:57:56 +00002356 """
Tim Peters19397e52004-08-06 22:02:59 +00002357
Jim Fulton07a349c2004-08-22 14:10:00 +00002358def test_trailing_space_in_test():
2359 """
Tim Petersa7def722004-08-23 22:13:22 +00002360 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002361
Jim Fulton07a349c2004-08-22 14:10:00 +00002362 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002363 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002364 foo \n
2365 """
Tim Peters19397e52004-08-06 22:02:59 +00002366
Jim Fultonf54bad42004-08-28 14:57:56 +00002367
2368def test_unittest_reportflags():
2369 """Default unittest reporting flags can be set to control reporting
2370
2371 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2372 only the first failure of each test. First, we'll look at the
2373 output without the flag. The file test_doctest.txt file has two
2374 tests. They both fail if blank lines are disabled:
2375
2376 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2377 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2378 >>> import unittest
2379 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002380 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002381 Traceback ...
2382 Failed example:
2383 favorite_color
2384 ...
2385 Failed example:
2386 if 1:
2387 ...
2388
2389 Note that we see both failures displayed.
2390
2391 >>> old = doctest.set_unittest_reportflags(
2392 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2393
2394 Now, when we run the test:
2395
2396 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002397 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002398 Traceback ...
2399 Failed example:
2400 favorite_color
2401 Exception raised:
2402 ...
2403 NameError: name 'favorite_color' is not defined
2404 <BLANKLINE>
2405 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002406
Jim Fultonf54bad42004-08-28 14:57:56 +00002407 We get only the first failure.
2408
2409 If we give any reporting options when we set up the tests,
2410 however:
2411
2412 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2413 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2414
2415 Then the default eporting options are ignored:
2416
2417 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002418 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002419 Traceback ...
2420 Failed example:
2421 favorite_color
2422 ...
2423 Failed example:
2424 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002425 print('a')
2426 print()
2427 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002428 Differences (ndiff with -expected +actual):
2429 a
2430 - <BLANKLINE>
2431 +
2432 b
2433 <BLANKLINE>
2434 <BLANKLINE>
2435
2436
2437 Test runners can restore the formatting flags after they run:
2438
2439 >>> ignored = doctest.set_unittest_reportflags(old)
2440
2441 """
2442
Edward Loper052d0cd2004-09-19 17:19:33 +00002443def test_testfile(): r"""
2444Tests for the `testfile()` function. This function runs all the
2445doctest examples in a given file. In its simple invokation, it is
2446called with the name of a file, which is taken to be relative to the
2447calling module. The return value is (#failures, #tests).
2448
Florent Xicluna59250852010-02-27 14:21:57 +00002449We don't want `-v` in sys.argv for these tests.
2450
2451 >>> save_argv = sys.argv
2452 >>> if '-v' in sys.argv:
2453 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2454
2455
Edward Loper052d0cd2004-09-19 17:19:33 +00002456 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2457 **********************************************************************
2458 File "...", line 6, in test_doctest.txt
2459 Failed example:
2460 favorite_color
2461 Exception raised:
2462 ...
2463 NameError: name 'favorite_color' is not defined
2464 **********************************************************************
2465 1 items had failures:
2466 1 of 2 in test_doctest.txt
2467 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002468 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002469 >>> doctest.master = None # Reset master.
2470
2471(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002472`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002473same name.)
2474
2475Globals may be specified with the `globs` and `extraglobs` parameters:
2476
2477 >>> globs = {'favorite_color': 'blue'}
2478 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002479 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002480 >>> doctest.master = None # Reset master.
2481
2482 >>> extraglobs = {'favorite_color': 'red'}
2483 >>> doctest.testfile('test_doctest.txt', globs=globs,
2484 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2485 **********************************************************************
2486 File "...", line 6, in test_doctest.txt
2487 Failed example:
2488 favorite_color
2489 Expected:
2490 'blue'
2491 Got:
2492 'red'
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
2500The file may be made relative to a given module or package, using the
2501optional `module_relative` parameter:
2502
2503 >>> doctest.testfile('test_doctest.txt', globs=globs,
2504 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002505 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002506 >>> doctest.master = None # Reset master.
2507
Ezio Melotti13925002011-03-16 11:05:33 +02002508Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002509
2510 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2511 Trying:
2512 favorite_color
2513 Expecting:
2514 'blue'
2515 ok
2516 Trying:
2517 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002518 print('a')
2519 print()
2520 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002521 Expecting:
2522 a
2523 <BLANKLINE>
2524 b
2525 ok
2526 1 items passed all tests:
2527 2 tests in test_doctest.txt
2528 2 tests in 1 items.
2529 2 passed and 0 failed.
2530 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002531 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002532 >>> doctest.master = None # Reset master.
2533
2534The name of the test may be specified with the optional `name`
2535parameter:
2536
2537 >>> doctest.testfile('test_doctest.txt', name='newname')
2538 ... # doctest: +ELLIPSIS
2539 **********************************************************************
2540 File "...", line 6, in newname
2541 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002542 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002543 >>> doctest.master = None # Reset master.
2544
Ezio Melotti13925002011-03-16 11:05:33 +02002545The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002546parameter:
2547
2548 >>> doctest.testfile('test_doctest.txt', report=False)
2549 ... # doctest: +ELLIPSIS
2550 **********************************************************************
2551 File "...", line 6, in test_doctest.txt
2552 Failed example:
2553 favorite_color
2554 Exception raised:
2555 ...
2556 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002557 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002558 >>> doctest.master = None # Reset master.
2559
2560The optional keyword argument `raise_on_error` can be used to raise an
2561exception on the first error (which may be useful for postmortem
2562debugging):
2563
2564 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2565 ... # doctest: +ELLIPSIS
2566 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002567 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002568 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002569
2570If the tests contain non-ASCII characters, the tests might fail, since
2571it's unknown which encoding is used. The encoding can be specified
2572using the optional keyword argument `encoding`:
2573
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002574 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002575 **********************************************************************
2576 File "...", line 7, in test_doctest4.txt
2577 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002578 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002579 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002580 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002581 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002582 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002583 **********************************************************************
2584 ...
2585 **********************************************************************
2586 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002587 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002588 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002589 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002590 >>> doctest.master = None # Reset master.
2591
2592 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002593 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002594 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002595
2596Test the verbose output:
2597
2598 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2599 Trying:
2600 'föö'
2601 Expecting:
2602 'f\xf6\xf6'
2603 ok
2604 Trying:
2605 'bÄ…r'
2606 Expecting:
2607 'b\u0105r'
2608 ok
2609 1 items passed all tests:
2610 2 tests in test_doctest4.txt
2611 2 tests in 1 items.
2612 2 passed and 0 failed.
2613 Test passed.
2614 TestResults(failed=0, attempted=2)
2615 >>> doctest.master = None # Reset master.
2616 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002617"""
2618
R David Murrayb48cb292014-10-02 22:42:42 -04002619def test_lineendings(): r"""
2620*nix systems use \n line endings, while Windows systems use \r\n. Python
2621handles this using universal newline mode for reading files. Let's make
2622sure doctest does so (issue 8473) by creating temporary test files using each
2623of the two line disciplines. One of the two will be the "wrong" one for the
2624platform the test is run on.
2625
2626Windows line endings first:
2627
2628 >>> import tempfile, os
2629 >>> fn = tempfile.mktemp()
2630 >>> with open(fn, 'w') as f:
2631 ... f.write('Test:\r\n\r\n >>> x = 1 + 1\r\n\r\nDone.\r\n')
2632 35
2633 >>> doctest.testfile(fn, False)
2634 TestResults(failed=0, attempted=1)
2635 >>> os.remove(fn)
2636
2637And now *nix line endings:
2638
2639 >>> fn = tempfile.mktemp()
2640 >>> with open(fn, 'w') as f:
2641 ... f.write('Test:\n\n >>> x = 1 + 1\n\nDone.\n')
2642 30
2643 >>> doctest.testfile(fn, False)
2644 TestResults(failed=0, attempted=1)
2645 >>> os.remove(fn)
2646
2647"""
2648
R. David Murray58641de2009-06-12 15:33:19 +00002649def test_testmod(): r"""
2650Tests for the testmod function. More might be useful, but for now we're just
2651testing the case raised by Issue 6195, where trying to doctest a C module would
2652fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2653out of the binary module.
2654
2655 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002656 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002657 TestResults(failed=0, attempted=0)
2658"""
2659
Victor Stinner9d396392010-10-16 21:54:59 +00002660try:
2661 os.fsencode("foo-bär@baz.py")
2662except UnicodeEncodeError:
2663 # Skip the test: the filesystem encoding is unable to encode the filename
2664 pass
2665else:
2666 def test_unicode(): """
2667Check doctest with a non-ascii filename:
2668
2669 >>> doc = '''
2670 ... >>> raise Exception('clé')
2671 ... '''
2672 ...
2673 >>> parser = doctest.DocTestParser()
2674 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2675 >>> test
2676 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2677 >>> runner = doctest.DocTestRunner(verbose=False)
2678 >>> runner.run(test) # doctest: +ELLIPSIS
2679 **********************************************************************
2680 File "foo-bär@baz.py", line 2, in foo-bär@baz
2681 Failed example:
2682 raise Exception('clé')
2683 Exception raised:
2684 Traceback (most recent call last):
2685 File ...
2686 compileflags, 1), test.globs)
2687 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2688 raise Exception('clé')
2689 Exception: clé
2690 TestResults(failed=1, attempted=1)
2691 """
2692
R David Murray5707d502013-06-23 14:24:13 -04002693def test_CLI(): r"""
2694The doctest module can be used to run doctests against an arbitrary file.
2695These tests test this CLI functionality.
2696
2697We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002698to a temp dir to run the command against. Due to a current limitation in
2699script_helpers, though, we need a little utility function to turn the returned
2700output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002701
R David Murray4af68982013-06-25 08:11:22 -04002702 >>> def normalize(s):
2703 ... return '\n'.join(s.decode().splitlines())
2704
2705Note: we also pass TERM='' to all the assert_python calls to avoid a bug
2706in the readline library that is triggered in these tests because we are
2707running them in a new python process. See:
2708
2709 http://lists.gnu.org/archive/html/bug-readline/2013-06/msg00000.html
2710
2711With those preliminaries out of the way, we'll start with a file with two
2712simple tests and no errors. We'll run both the unadorned doctest command, and
2713the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002714
2715 >>> from test import script_helper
2716 >>> with script_helper.temp_dir() as tmpdir:
2717 ... fn = os.path.join(tmpdir, 'myfile.doc')
2718 ... with open(fn, 'w') as f:
2719 ... _ = f.write('This is a very simple test file.\n')
2720 ... _ = f.write(' >>> 1 + 1\n')
2721 ... _ = f.write(' 2\n')
2722 ... _ = f.write(' >>> "a"\n')
2723 ... _ = f.write(" 'a'\n")
2724 ... _ = f.write('\n')
2725 ... _ = f.write('And that is it.\n')
2726 ... rc1, out1, err1 = script_helper.assert_python_ok(
R David Murray4af68982013-06-25 08:11:22 -04002727 ... '-m', 'doctest', fn, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002728 ... rc2, out2, err2 = script_helper.assert_python_ok(
R David Murray4af68982013-06-25 08:11:22 -04002729 ... '-m', 'doctest', '-v', fn, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002730
2731With no arguments and passing tests, we should get no output:
2732
2733 >>> rc1, out1, err1
2734 (0, b'', b'')
2735
2736With the verbose flag, we should see the test output, but no error output:
2737
2738 >>> rc2, err2
2739 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002740 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002741 Trying:
2742 1 + 1
2743 Expecting:
2744 2
2745 ok
2746 Trying:
2747 "a"
2748 Expecting:
2749 'a'
2750 ok
2751 1 items passed all tests:
2752 2 tests in myfile.doc
2753 2 tests in 1 items.
2754 2 passed and 0 failed.
2755 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002756
2757Now we'll write a couple files, one with three tests, the other a python module
2758with two tests, both of the files having "errors" in the tests that can be made
2759non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2760the first file, NORMALIZE_WHITESPACE in the second). This combination will
2761allow to thoroughly test the -f and -o flags, as well as the doctest command's
2762ability to process more than one file on the command line and, since the second
2763file ends in '.py', its handling of python module files (as opposed to straight
2764text files).
2765
2766 >>> from test import script_helper
2767 >>> with script_helper.temp_dir() as tmpdir:
2768 ... fn = os.path.join(tmpdir, 'myfile.doc')
2769 ... with open(fn, 'w') as f:
2770 ... _ = f.write('This is another simple test file.\n')
2771 ... _ = f.write(' >>> 1 + 1\n')
2772 ... _ = f.write(' 2\n')
2773 ... _ = f.write(' >>> "abcdef"\n')
2774 ... _ = f.write(" 'a...f'\n")
2775 ... _ = f.write(' >>> "ajkml"\n')
2776 ... _ = f.write(" 'a...l'\n")
2777 ... _ = f.write('\n')
2778 ... _ = f.write('And that is it.\n')
2779 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2780 ... with open(fn2, 'w') as f:
2781 ... _ = f.write('def test_func():\n')
2782 ... _ = f.write(' \"\"\"\n')
2783 ... _ = f.write(' This is simple python test function.\n')
2784 ... _ = f.write(' >>> 1 + 1\n')
2785 ... _ = f.write(' 2\n')
2786 ... _ = f.write(' >>> "abc def"\n')
2787 ... _ = f.write(" 'abc def'\n")
2788 ... _ = f.write("\n")
2789 ... _ = f.write(' \"\"\"\n')
2790 ... import shutil
2791 ... rc1, out1, err1 = script_helper.assert_python_failure(
R David Murray4af68982013-06-25 08:11:22 -04002792 ... '-m', 'doctest', fn, fn2, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002793 ... rc2, out2, err2 = script_helper.assert_python_ok(
R David Murray4af68982013-06-25 08:11:22 -04002794 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002795 ... rc3, out3, err3 = script_helper.assert_python_ok(
2796 ... '-m', 'doctest', '-o', 'ELLIPSIS',
R David Murray4af68982013-06-25 08:11:22 -04002797 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002798 ... rc4, out4, err4 = script_helper.assert_python_failure(
R David Murray4af68982013-06-25 08:11:22 -04002799 ... '-m', 'doctest', '-f', fn, fn2, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002800 ... rc5, out5, err5 = script_helper.assert_python_ok(
2801 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
R David Murray4af68982013-06-25 08:11:22 -04002802 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002803
2804Our first test run will show the errors from the first file (doctest stops if a
2805file has errors). Note that doctest test-run error output appears on stdout,
2806not stderr:
2807
2808 >>> rc1, err1
2809 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002810 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002811 **********************************************************************
2812 File "...myfile.doc", line 4, in myfile.doc
2813 Failed example:
2814 "abcdef"
2815 Expected:
2816 'a...f'
2817 Got:
2818 'abcdef'
2819 **********************************************************************
2820 File "...myfile.doc", line 6, in myfile.doc
2821 Failed example:
2822 "ajkml"
2823 Expected:
2824 'a...l'
2825 Got:
2826 'ajkml'
2827 **********************************************************************
2828 1 items had failures:
2829 2 of 3 in myfile.doc
2830 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002831
2832With -o ELLIPSIS specified, the second run, against just the first file, should
2833produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2834should the third, which ran against both files:
2835
2836 >>> rc2, out2, err2
2837 (0, b'', b'')
2838 >>> rc3, out3, err3
2839 (0, b'', b'')
2840
2841The fourth run uses FAIL_FAST, so we should see only one error:
2842
2843 >>> rc4, err4
2844 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002845 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002846 **********************************************************************
2847 File "...myfile.doc", line 4, in myfile.doc
2848 Failed example:
2849 "abcdef"
2850 Expected:
2851 'a...f'
2852 Got:
2853 'abcdef'
2854 **********************************************************************
2855 1 items had failures:
2856 1 of 2 in myfile.doc
2857 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002858
2859The fifth test uses verbose with the two options, so we should get verbose
2860success output for the tests in both files:
2861
2862 >>> rc5, err5
2863 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002864 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002865 Trying:
2866 1 + 1
2867 Expecting:
2868 2
2869 ok
2870 Trying:
2871 "abcdef"
2872 Expecting:
2873 'a...f'
2874 ok
2875 Trying:
2876 "ajkml"
2877 Expecting:
2878 'a...l'
2879 ok
2880 1 items passed all tests:
2881 3 tests in myfile.doc
2882 3 tests in 1 items.
2883 3 passed and 0 failed.
2884 Test passed.
2885 Trying:
2886 1 + 1
2887 Expecting:
2888 2
2889 ok
2890 Trying:
2891 "abc def"
2892 Expecting:
2893 'abc def'
2894 ok
2895 1 items had no tests:
2896 myfile2
2897 1 items passed all tests:
2898 2 tests in myfile2.test_func
2899 2 tests in 2 items.
2900 2 passed and 0 failed.
2901 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002902
2903We should also check some typical error cases.
2904
2905Invalid file name:
2906
2907 >>> rc, out, err = script_helper.assert_python_failure(
R David Murray4af68982013-06-25 08:11:22 -04002908 ... '-m', 'doctest', 'nosuchfile', TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002909 >>> rc, out
2910 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002911 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002912 Traceback (most recent call last):
2913 ...
2914 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
2915
2916Invalid doctest option:
2917
2918 >>> rc, out, err = script_helper.assert_python_failure(
R David Murray4af68982013-06-25 08:11:22 -04002919 ... '-m', 'doctest', '-o', 'nosuchoption', TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002920 >>> rc, out
2921 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04002922 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002923 usage...invalid...nosuchoption...
2924
2925"""
2926
Tim Peters8485b562004-08-04 18:46:34 +00002927######################################################################
2928## Main
2929######################################################################
2930
2931def test_main():
2932 # Check the doctest cases in doctest itself:
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02002933 ret = support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002934 # Check the doctest cases defined here:
2935 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002936 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002937
Victor Stinner45df8202010-04-28 22:31:17 +00002938import sys, re, io
2939
Tim Peters8485b562004-08-04 18:46:34 +00002940def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002941 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01002942 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00002943 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002944 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002945 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002946 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002947 r.write_results(show_missing=True, summary=True,
2948 coverdir=coverdir)
2949
2950if __name__ == '__main__':
2951 if '-c' in sys.argv:
2952 test_coverage('/tmp/doctest.cover')
2953 else:
2954 test_main()