blob: 56193e87b1c9d446c6895b23cea0e1b55510c22c [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
2099 However, if DocTestSuite finds no docstrings, it raises an error:
2100
2101 >>> try:
2102 ... doctest.DocTestSuite('test.sample_doctest_no_docstrings')
2103 ... except ValueError as e:
2104 ... error = e
2105
2106 >>> print(error.args[1])
2107 has no docstrings
2108
2109 You can prevent this error by passing a DocTestFinder instance with
2110 the `exclude_empty` keyword argument set to False:
2111
2112 >>> finder = doctest.DocTestFinder(exclude_empty=False)
2113 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2114 ... test_finder=finder)
2115 >>> suite.run(unittest.TestResult())
2116 <unittest.result.TestResult run=0 errors=0 failures=0>
2117
Tim Peters19397e52004-08-06 22:02:59 +00002118 We can use the current module:
2119
2120 >>> suite = test.sample_doctest.test_suite()
2121 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002122 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002123
2124 We can supply global variables. If we pass globs, they will be
2125 used instead of the module globals. Here we'll pass an empty
2126 globals, triggering an extra error:
2127
2128 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2129 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002130 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002131
2132 Alternatively, we can provide extra globals. Here we'll make an
2133 error go away by providing an extra global variable:
2134
2135 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2136 ... extraglobs={'y': 1})
2137 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002138 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002139
2140 You can pass option flags. Here we'll cause an extra error
2141 by disabling the blank-line feature:
2142
2143 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002144 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002145 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002146 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002147
Tim Peters1e277ee2004-08-07 05:37:52 +00002148 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002149
Jim Fultonf54bad42004-08-28 14:57:56 +00002150 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002151 ... import test.test_doctest
2152 ... test.test_doctest.sillySetup = True
2153
Jim Fultonf54bad42004-08-28 14:57:56 +00002154 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002155 ... import test.test_doctest
2156 ... del test.test_doctest.sillySetup
2157
2158 Here, we installed a silly variable that the test expects:
2159
2160 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2161 ... setUp=setUp, tearDown=tearDown)
2162 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002163 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002164
2165 But the tearDown restores sanity:
2166
2167 >>> import test.test_doctest
2168 >>> test.test_doctest.sillySetup
2169 Traceback (most recent call last):
2170 ...
2171 AttributeError: 'module' object has no attribute 'sillySetup'
2172
Jim Fultonf54bad42004-08-28 14:57:56 +00002173 The setUp and tearDown funtions are passed test objects. Here
2174 we'll use the setUp function to supply the missing variable y:
2175
2176 >>> def setUp(test):
2177 ... test.globs['y'] = 1
2178
2179 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2180 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002181 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002182
2183 Here, we didn't need to use a tearDown function because we
2184 modified the test globals, which are a copy of the
2185 sample_doctest module dictionary. The test globals are
2186 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002187 """
2188
2189def test_DocFileSuite():
2190 """We can test tests found in text files using a DocFileSuite.
2191
2192 We create a suite by providing the names of one or more text
2193 files that include examples:
2194
2195 >>> import unittest
2196 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002197 ... 'test_doctest2.txt',
2198 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002199 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002200 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002201
2202 The test files are looked for in the directory containing the
2203 calling module. A package keyword argument can be provided to
2204 specify a different relative location.
2205
2206 >>> import unittest
2207 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2208 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002209 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002210 ... package='test')
2211 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002212 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002213
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002214 Support for using a package's __loader__.get_data() is also
2215 provided.
2216
2217 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002218 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002219 >>> if not hasattr(test, '__loader__'):
2220 ... test.__loader__ = pkgutil.get_loader(test)
2221 ... added_loader = True
2222 >>> try:
2223 ... suite = doctest.DocFileSuite('test_doctest.txt',
2224 ... 'test_doctest2.txt',
2225 ... 'test_doctest4.txt',
2226 ... package='test')
2227 ... suite.run(unittest.TestResult())
2228 ... finally:
2229 ... if added_loader:
2230 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002231 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002232
Edward Loper0273f5b2004-09-18 20:27:04 +00002233 '/' should be used as a path separator. It will be converted
2234 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002235
2236 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2237 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002238 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002239
Edward Loper0273f5b2004-09-18 20:27:04 +00002240 If DocFileSuite is used from an interactive session, then files
2241 are resolved relative to the directory of sys.argv[0]:
2242
Christian Heimes45f9af32007-11-27 21:50:00 +00002243 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002244 >>> save_argv = sys.argv
2245 >>> sys.argv = [test.test_doctest.__file__]
2246 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002247 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002248 >>> sys.argv = save_argv
2249
Edward Loper052d0cd2004-09-19 17:19:33 +00002250 By setting `module_relative=False`, os-specific paths may be
2251 used (including absolute paths and paths relative to the
2252 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002253
2254 >>> # Get the absolute path of the test package.
2255 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2256 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2257
2258 >>> # Use it to find the absolute path of test_doctest.txt.
2259 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2260
Edward Loper052d0cd2004-09-19 17:19:33 +00002261 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002262 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002263 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002264
Edward Loper052d0cd2004-09-19 17:19:33 +00002265 It is an error to specify `package` when `module_relative=False`:
2266
2267 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2268 ... package='test')
2269 Traceback (most recent call last):
2270 ValueError: Package may only be specified for module-relative paths.
2271
Tim Peters19397e52004-08-06 22:02:59 +00002272 You can specify initial global variables:
2273
2274 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2275 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002276 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002277 ... globs={'favorite_color': 'blue'})
2278 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002279 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002280
2281 In this case, we supplied a missing favorite color. You can
2282 provide doctest options:
2283
2284 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2285 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002286 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002287 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2288 ... globs={'favorite_color': 'blue'})
2289 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002290 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002291
2292 And, you can provide setUp and tearDown functions:
2293
Jim Fultonf54bad42004-08-28 14:57:56 +00002294 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002295 ... import test.test_doctest
2296 ... test.test_doctest.sillySetup = True
2297
Jim Fultonf54bad42004-08-28 14:57:56 +00002298 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002299 ... import test.test_doctest
2300 ... del test.test_doctest.sillySetup
2301
2302 Here, we installed a silly variable that the test expects:
2303
2304 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2305 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002306 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002307 ... setUp=setUp, tearDown=tearDown)
2308 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002309 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002310
2311 But the tearDown restores sanity:
2312
2313 >>> import test.test_doctest
2314 >>> test.test_doctest.sillySetup
2315 Traceback (most recent call last):
2316 ...
2317 AttributeError: 'module' object has no attribute 'sillySetup'
2318
Jim Fultonf54bad42004-08-28 14:57:56 +00002319 The setUp and tearDown funtions are passed test objects.
2320 Here, we'll use a setUp function to set the favorite color in
2321 test_doctest.txt:
2322
2323 >>> def setUp(test):
2324 ... test.globs['favorite_color'] = 'blue'
2325
2326 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2327 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002328 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002329
2330 Here, we didn't need to use a tearDown function because we
2331 modified the test globals. The test globals are
2332 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002333
Fred Drake7c404a42004-12-21 23:46:34 +00002334 Tests in a file run using `DocFileSuite` can also access the
2335 `__file__` global, which is set to the name of the file
2336 containing the tests:
2337
2338 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2339 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002340 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002341
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002342 If the tests contain non-ASCII characters, we have to specify which
2343 encoding the file is encoded with. We do so by using the `encoding`
2344 parameter:
2345
2346 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2347 ... 'test_doctest2.txt',
2348 ... 'test_doctest4.txt',
2349 ... encoding='utf-8')
2350 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002351 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002352
Jim Fultonf54bad42004-08-28 14:57:56 +00002353 """
Tim Peters19397e52004-08-06 22:02:59 +00002354
Jim Fulton07a349c2004-08-22 14:10:00 +00002355def test_trailing_space_in_test():
2356 """
Tim Petersa7def722004-08-23 22:13:22 +00002357 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002358
Jim Fulton07a349c2004-08-22 14:10:00 +00002359 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002360 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002361 foo \n
2362 """
Tim Peters19397e52004-08-06 22:02:59 +00002363
Jim Fultonf54bad42004-08-28 14:57:56 +00002364
2365def test_unittest_reportflags():
2366 """Default unittest reporting flags can be set to control reporting
2367
2368 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2369 only the first failure of each test. First, we'll look at the
2370 output without the flag. The file test_doctest.txt file has two
2371 tests. They both fail if blank lines are disabled:
2372
2373 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2374 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2375 >>> import unittest
2376 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002377 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002378 Traceback ...
2379 Failed example:
2380 favorite_color
2381 ...
2382 Failed example:
2383 if 1:
2384 ...
2385
2386 Note that we see both failures displayed.
2387
2388 >>> old = doctest.set_unittest_reportflags(
2389 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2390
2391 Now, when we run the test:
2392
2393 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002394 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002395 Traceback ...
2396 Failed example:
2397 favorite_color
2398 Exception raised:
2399 ...
2400 NameError: name 'favorite_color' is not defined
2401 <BLANKLINE>
2402 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002403
Jim Fultonf54bad42004-08-28 14:57:56 +00002404 We get only the first failure.
2405
2406 If we give any reporting options when we set up the tests,
2407 however:
2408
2409 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2410 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2411
2412 Then the default eporting options are ignored:
2413
2414 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002415 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002416 Traceback ...
2417 Failed example:
2418 favorite_color
2419 ...
2420 Failed example:
2421 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002422 print('a')
2423 print()
2424 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002425 Differences (ndiff with -expected +actual):
2426 a
2427 - <BLANKLINE>
2428 +
2429 b
2430 <BLANKLINE>
2431 <BLANKLINE>
2432
2433
2434 Test runners can restore the formatting flags after they run:
2435
2436 >>> ignored = doctest.set_unittest_reportflags(old)
2437
2438 """
2439
Edward Loper052d0cd2004-09-19 17:19:33 +00002440def test_testfile(): r"""
2441Tests for the `testfile()` function. This function runs all the
2442doctest examples in a given file. In its simple invokation, it is
2443called with the name of a file, which is taken to be relative to the
2444calling module. The return value is (#failures, #tests).
2445
Florent Xicluna59250852010-02-27 14:21:57 +00002446We don't want `-v` in sys.argv for these tests.
2447
2448 >>> save_argv = sys.argv
2449 >>> if '-v' in sys.argv:
2450 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2451
2452
Edward Loper052d0cd2004-09-19 17:19:33 +00002453 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2454 **********************************************************************
2455 File "...", line 6, in test_doctest.txt
2456 Failed example:
2457 favorite_color
2458 Exception raised:
2459 ...
2460 NameError: name 'favorite_color' is not defined
2461 **********************************************************************
2462 1 items had failures:
2463 1 of 2 in test_doctest.txt
2464 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002465 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002466 >>> doctest.master = None # Reset master.
2467
2468(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002469`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002470same name.)
2471
2472Globals may be specified with the `globs` and `extraglobs` parameters:
2473
2474 >>> globs = {'favorite_color': 'blue'}
2475 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002476 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002477 >>> doctest.master = None # Reset master.
2478
2479 >>> extraglobs = {'favorite_color': 'red'}
2480 >>> doctest.testfile('test_doctest.txt', globs=globs,
2481 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2482 **********************************************************************
2483 File "...", line 6, in test_doctest.txt
2484 Failed example:
2485 favorite_color
2486 Expected:
2487 'blue'
2488 Got:
2489 'red'
2490 **********************************************************************
2491 1 items had failures:
2492 1 of 2 in test_doctest.txt
2493 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002494 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002495 >>> doctest.master = None # Reset master.
2496
2497The file may be made relative to a given module or package, using the
2498optional `module_relative` parameter:
2499
2500 >>> doctest.testfile('test_doctest.txt', globs=globs,
2501 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002502 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002503 >>> doctest.master = None # Reset master.
2504
Ezio Melotti13925002011-03-16 11:05:33 +02002505Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002506
2507 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2508 Trying:
2509 favorite_color
2510 Expecting:
2511 'blue'
2512 ok
2513 Trying:
2514 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002515 print('a')
2516 print()
2517 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002518 Expecting:
2519 a
2520 <BLANKLINE>
2521 b
2522 ok
2523 1 items passed all tests:
2524 2 tests in test_doctest.txt
2525 2 tests in 1 items.
2526 2 passed and 0 failed.
2527 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002528 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002529 >>> doctest.master = None # Reset master.
2530
2531The name of the test may be specified with the optional `name`
2532parameter:
2533
2534 >>> doctest.testfile('test_doctest.txt', name='newname')
2535 ... # doctest: +ELLIPSIS
2536 **********************************************************************
2537 File "...", line 6, in newname
2538 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002539 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002540 >>> doctest.master = None # Reset master.
2541
Ezio Melotti13925002011-03-16 11:05:33 +02002542The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002543parameter:
2544
2545 >>> doctest.testfile('test_doctest.txt', report=False)
2546 ... # doctest: +ELLIPSIS
2547 **********************************************************************
2548 File "...", line 6, in test_doctest.txt
2549 Failed example:
2550 favorite_color
2551 Exception raised:
2552 ...
2553 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002554 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002555 >>> doctest.master = None # Reset master.
2556
2557The optional keyword argument `raise_on_error` can be used to raise an
2558exception on the first error (which may be useful for postmortem
2559debugging):
2560
2561 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2562 ... # doctest: +ELLIPSIS
2563 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002564 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002565 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002566
2567If the tests contain non-ASCII characters, the tests might fail, since
2568it's unknown which encoding is used. The encoding can be specified
2569using the optional keyword argument `encoding`:
2570
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002571 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002572 **********************************************************************
2573 File "...", line 7, in test_doctest4.txt
2574 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002575 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002576 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002577 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002578 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002579 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002580 **********************************************************************
2581 ...
2582 **********************************************************************
2583 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002584 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002585 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002586 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002587 >>> doctest.master = None # Reset master.
2588
2589 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002590 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002591 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002592
2593Test the verbose output:
2594
2595 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2596 Trying:
2597 'föö'
2598 Expecting:
2599 'f\xf6\xf6'
2600 ok
2601 Trying:
2602 'bÄ…r'
2603 Expecting:
2604 'b\u0105r'
2605 ok
2606 1 items passed all tests:
2607 2 tests in test_doctest4.txt
2608 2 tests in 1 items.
2609 2 passed and 0 failed.
2610 Test passed.
2611 TestResults(failed=0, attempted=2)
2612 >>> doctest.master = None # Reset master.
2613 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002614"""
2615
R. David Murray58641de2009-06-12 15:33:19 +00002616def test_testmod(): r"""
2617Tests for the testmod function. More might be useful, but for now we're just
2618testing the case raised by Issue 6195, where trying to doctest a C module would
2619fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2620out of the binary module.
2621
2622 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002623 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002624 TestResults(failed=0, attempted=0)
2625"""
2626
Victor Stinner9d396392010-10-16 21:54:59 +00002627try:
2628 os.fsencode("foo-bär@baz.py")
2629except UnicodeEncodeError:
2630 # Skip the test: the filesystem encoding is unable to encode the filename
2631 pass
2632else:
2633 def test_unicode(): """
2634Check doctest with a non-ascii filename:
2635
2636 >>> doc = '''
2637 ... >>> raise Exception('clé')
2638 ... '''
2639 ...
2640 >>> parser = doctest.DocTestParser()
2641 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2642 >>> test
2643 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2644 >>> runner = doctest.DocTestRunner(verbose=False)
2645 >>> runner.run(test) # doctest: +ELLIPSIS
2646 **********************************************************************
2647 File "foo-bär@baz.py", line 2, in foo-bär@baz
2648 Failed example:
2649 raise Exception('clé')
2650 Exception raised:
2651 Traceback (most recent call last):
2652 File ...
2653 compileflags, 1), test.globs)
2654 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2655 raise Exception('clé')
2656 Exception: clé
2657 TestResults(failed=1, attempted=1)
2658 """
2659
R David Murray5707d502013-06-23 14:24:13 -04002660def test_CLI(): r"""
2661The doctest module can be used to run doctests against an arbitrary file.
2662These tests test this CLI functionality.
2663
2664We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002665to a temp dir to run the command against. Due to a current limitation in
2666script_helpers, though, we need a little utility function to turn the returned
2667output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002668
R David Murray4af68982013-06-25 08:11:22 -04002669 >>> def normalize(s):
2670 ... return '\n'.join(s.decode().splitlines())
2671
2672Note: we also pass TERM='' to all the assert_python calls to avoid a bug
2673in the readline library that is triggered in these tests because we are
2674running them in a new python process. See:
2675
2676 http://lists.gnu.org/archive/html/bug-readline/2013-06/msg00000.html
2677
2678With those preliminaries out of the way, we'll start with a file with two
2679simple tests and no errors. We'll run both the unadorned doctest command, and
2680the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002681
2682 >>> from test import script_helper
2683 >>> with script_helper.temp_dir() as tmpdir:
2684 ... fn = os.path.join(tmpdir, 'myfile.doc')
2685 ... with open(fn, 'w') as f:
2686 ... _ = f.write('This is a very simple test file.\n')
2687 ... _ = f.write(' >>> 1 + 1\n')
2688 ... _ = f.write(' 2\n')
2689 ... _ = f.write(' >>> "a"\n')
2690 ... _ = f.write(" 'a'\n")
2691 ... _ = f.write('\n')
2692 ... _ = f.write('And that is it.\n')
2693 ... rc1, out1, err1 = script_helper.assert_python_ok(
R David Murray4af68982013-06-25 08:11:22 -04002694 ... '-m', 'doctest', fn, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002695 ... rc2, out2, err2 = script_helper.assert_python_ok(
R David Murray4af68982013-06-25 08:11:22 -04002696 ... '-m', 'doctest', '-v', fn, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002697
2698With no arguments and passing tests, we should get no output:
2699
2700 >>> rc1, out1, err1
2701 (0, b'', b'')
2702
2703With the verbose flag, we should see the test output, but no error output:
2704
2705 >>> rc2, err2
2706 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002707 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002708 Trying:
2709 1 + 1
2710 Expecting:
2711 2
2712 ok
2713 Trying:
2714 "a"
2715 Expecting:
2716 'a'
2717 ok
2718 1 items passed all tests:
2719 2 tests in myfile.doc
2720 2 tests in 1 items.
2721 2 passed and 0 failed.
2722 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002723
2724Now we'll write a couple files, one with three tests, the other a python module
2725with two tests, both of the files having "errors" in the tests that can be made
2726non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2727the first file, NORMALIZE_WHITESPACE in the second). This combination will
2728allow to thoroughly test the -f and -o flags, as well as the doctest command's
2729ability to process more than one file on the command line and, since the second
2730file ends in '.py', its handling of python module files (as opposed to straight
2731text files).
2732
2733 >>> from test import script_helper
2734 >>> with script_helper.temp_dir() as tmpdir:
2735 ... fn = os.path.join(tmpdir, 'myfile.doc')
2736 ... with open(fn, 'w') as f:
2737 ... _ = f.write('This is another simple test file.\n')
2738 ... _ = f.write(' >>> 1 + 1\n')
2739 ... _ = f.write(' 2\n')
2740 ... _ = f.write(' >>> "abcdef"\n')
2741 ... _ = f.write(" 'a...f'\n")
2742 ... _ = f.write(' >>> "ajkml"\n')
2743 ... _ = f.write(" 'a...l'\n")
2744 ... _ = f.write('\n')
2745 ... _ = f.write('And that is it.\n')
2746 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2747 ... with open(fn2, 'w') as f:
2748 ... _ = f.write('def test_func():\n')
2749 ... _ = f.write(' \"\"\"\n')
2750 ... _ = f.write(' This is simple python test function.\n')
2751 ... _ = f.write(' >>> 1 + 1\n')
2752 ... _ = f.write(' 2\n')
2753 ... _ = f.write(' >>> "abc def"\n')
2754 ... _ = f.write(" 'abc def'\n")
2755 ... _ = f.write("\n")
2756 ... _ = f.write(' \"\"\"\n')
2757 ... import shutil
2758 ... rc1, out1, err1 = script_helper.assert_python_failure(
R David Murray4af68982013-06-25 08:11:22 -04002759 ... '-m', 'doctest', fn, fn2, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002760 ... rc2, out2, err2 = script_helper.assert_python_ok(
R David Murray4af68982013-06-25 08:11:22 -04002761 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002762 ... rc3, out3, err3 = script_helper.assert_python_ok(
2763 ... '-m', 'doctest', '-o', 'ELLIPSIS',
R David Murray4af68982013-06-25 08:11:22 -04002764 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002765 ... rc4, out4, err4 = script_helper.assert_python_failure(
R David Murray4af68982013-06-25 08:11:22 -04002766 ... '-m', 'doctest', '-f', fn, fn2, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002767 ... rc5, out5, err5 = script_helper.assert_python_ok(
2768 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
R David Murray4af68982013-06-25 08:11:22 -04002769 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002770
2771Our first test run will show the errors from the first file (doctest stops if a
2772file has errors). Note that doctest test-run error output appears on stdout,
2773not stderr:
2774
2775 >>> rc1, err1
2776 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002777 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002778 **********************************************************************
2779 File "...myfile.doc", line 4, in myfile.doc
2780 Failed example:
2781 "abcdef"
2782 Expected:
2783 'a...f'
2784 Got:
2785 'abcdef'
2786 **********************************************************************
2787 File "...myfile.doc", line 6, in myfile.doc
2788 Failed example:
2789 "ajkml"
2790 Expected:
2791 'a...l'
2792 Got:
2793 'ajkml'
2794 **********************************************************************
2795 1 items had failures:
2796 2 of 3 in myfile.doc
2797 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002798
2799With -o ELLIPSIS specified, the second run, against just the first file, should
2800produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2801should the third, which ran against both files:
2802
2803 >>> rc2, out2, err2
2804 (0, b'', b'')
2805 >>> rc3, out3, err3
2806 (0, b'', b'')
2807
2808The fourth run uses FAIL_FAST, so we should see only one error:
2809
2810 >>> rc4, err4
2811 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002812 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002813 **********************************************************************
2814 File "...myfile.doc", line 4, in myfile.doc
2815 Failed example:
2816 "abcdef"
2817 Expected:
2818 'a...f'
2819 Got:
2820 'abcdef'
2821 **********************************************************************
2822 1 items had failures:
2823 1 of 2 in myfile.doc
2824 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002825
2826The fifth test uses verbose with the two options, so we should get verbose
2827success output for the tests in both files:
2828
2829 >>> rc5, err5
2830 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002831 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002832 Trying:
2833 1 + 1
2834 Expecting:
2835 2
2836 ok
2837 Trying:
2838 "abcdef"
2839 Expecting:
2840 'a...f'
2841 ok
2842 Trying:
2843 "ajkml"
2844 Expecting:
2845 'a...l'
2846 ok
2847 1 items passed all tests:
2848 3 tests in myfile.doc
2849 3 tests in 1 items.
2850 3 passed and 0 failed.
2851 Test passed.
2852 Trying:
2853 1 + 1
2854 Expecting:
2855 2
2856 ok
2857 Trying:
2858 "abc def"
2859 Expecting:
2860 'abc def'
2861 ok
2862 1 items had no tests:
2863 myfile2
2864 1 items passed all tests:
2865 2 tests in myfile2.test_func
2866 2 tests in 2 items.
2867 2 passed and 0 failed.
2868 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002869
2870We should also check some typical error cases.
2871
2872Invalid file name:
2873
2874 >>> rc, out, err = script_helper.assert_python_failure(
R David Murray4af68982013-06-25 08:11:22 -04002875 ... '-m', 'doctest', 'nosuchfile', TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002876 >>> rc, out
2877 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002878 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002879 Traceback (most recent call last):
2880 ...
2881 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
2882
2883Invalid doctest option:
2884
2885 >>> rc, out, err = script_helper.assert_python_failure(
R David Murray4af68982013-06-25 08:11:22 -04002886 ... '-m', 'doctest', '-o', 'nosuchoption', TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002887 >>> rc, out
2888 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04002889 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002890 usage...invalid...nosuchoption...
2891
2892"""
2893
Tim Peters8485b562004-08-04 18:46:34 +00002894######################################################################
2895## Main
2896######################################################################
2897
2898def test_main():
2899 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002900 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002901 # Check the doctest cases defined here:
2902 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002903 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002904
Victor Stinner45df8202010-04-28 22:31:17 +00002905import sys, re, io
2906
Tim Peters8485b562004-08-04 18:46:34 +00002907def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002908 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01002909 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00002910 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002911 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002912 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002913 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002914 r.write_results(show_missing=True, summary=True,
2915 coverdir=coverdir)
2916
2917if __name__ == '__main__':
2918 if '-c' in sys.argv:
2919 test_coverage('/tmp/doctest.cover')
2920 else:
2921 test_main()