blob: 5b53ca8e02fd1f97321112f769e8e40b25310034 [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 Peters8485b562004-08-04 18:46:34 +00001057If an exception is raised but not expected, then it is reported as an
1058unexpected exception:
1059
Tim Peters8485b562004-08-04 18:46:34 +00001060 >>> def f(x):
1061 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001062 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001063 ... 0
1064 ... '''
1065 >>> test = doctest.DocTestFinder().find(f)[0]
1066 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001067 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001068 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001069 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001070 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001071 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001072 Exception raised:
1073 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001074 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001075 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001076 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001077"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001078 def displayhook(): r"""
1079Test that changing sys.displayhook doesn't matter for doctest.
1080
1081 >>> import sys
1082 >>> orig_displayhook = sys.displayhook
1083 >>> def my_displayhook(x):
1084 ... print('hi!')
1085 >>> sys.displayhook = my_displayhook
1086 >>> def f():
1087 ... '''
1088 ... >>> 3
1089 ... 3
1090 ... '''
1091 >>> test = doctest.DocTestFinder().find(f)[0]
1092 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1093 >>> post_displayhook = sys.displayhook
1094
1095 We need to restore sys.displayhook now, so that we'll be able to test
1096 results.
1097
1098 >>> sys.displayhook = orig_displayhook
1099
1100 Ok, now we can check that everything is ok.
1101
1102 >>> r
1103 TestResults(failed=0, attempted=1)
1104 >>> post_displayhook is my_displayhook
1105 True
1106"""
Tim Peters8485b562004-08-04 18:46:34 +00001107 def optionflags(): r"""
1108Tests of `DocTestRunner`'s option flag handling.
1109
1110Several option flags can be used to customize the behavior of the test
1111runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001112to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001113together).
1114
1115The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1116and 1/0:
1117
1118 >>> def f(x):
1119 ... '>>> True\n1\n'
1120
1121 >>> # Without the flag:
1122 >>> test = doctest.DocTestFinder().find(f)[0]
1123 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001124 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001125
1126 >>> # With the flag:
1127 >>> test = doctest.DocTestFinder().find(f)[0]
1128 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1129 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001130 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001131 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001132 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001133 Failed example:
1134 True
1135 Expected:
1136 1
1137 Got:
1138 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001139 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001140
1141The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1142and the '<BLANKLINE>' marker:
1143
1144 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001145 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001146
1147 >>> # Without the flag:
1148 >>> test = doctest.DocTestFinder().find(f)[0]
1149 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001150 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001151
1152 >>> # With the flag:
1153 >>> test = doctest.DocTestFinder().find(f)[0]
1154 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1155 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001156 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001157 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001158 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001159 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001160 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001161 Expected:
1162 a
1163 <BLANKLINE>
1164 b
1165 Got:
1166 a
1167 <BLANKLINE>
1168 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001169 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001170
1171The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1172treated as equal:
1173
1174 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001175 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001176
1177 >>> # Without the flag:
1178 >>> test = doctest.DocTestFinder().find(f)[0]
1179 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001180 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001181 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001182 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001183 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001184 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001185 Expected:
1186 1 2
1187 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001188 Got:
1189 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001190 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001191
1192 >>> # With the flag:
1193 >>> test = doctest.DocTestFinder().find(f)[0]
1194 >>> flags = doctest.NORMALIZE_WHITESPACE
1195 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001196 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001197
Tim Peters026f8dc2004-08-19 16:38:58 +00001198 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001199 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001200 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1201 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1202
Tim Peters8485b562004-08-04 18:46:34 +00001203The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1204output to match any substring in the actual output:
1205
1206 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001207 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001208
1209 >>> # Without the flag:
1210 >>> test = doctest.DocTestFinder().find(f)[0]
1211 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001212 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001213 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001214 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001215 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001216 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001217 Expected:
1218 [0, 1, 2, ..., 14]
1219 Got:
1220 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001221 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001222
1223 >>> # With the flag:
1224 >>> test = doctest.DocTestFinder().find(f)[0]
1225 >>> flags = doctest.ELLIPSIS
1226 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001227 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001228
Tim Peterse594bee2004-08-22 01:47:51 +00001229 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001230
Guido van Rossume0192e52007-02-09 23:39:59 +00001231 >>> if 1:
1232 ... for i in range(100):
1233 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1234 ... print('!')
1235 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001236
Tim Peters026f8dc2004-08-19 16:38:58 +00001237 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001238
Guido van Rossume0192e52007-02-09 23:39:59 +00001239 >>> if 1: #doctest: +ELLIPSIS
1240 ... for i in range(20):
1241 ... print(i, end=' ')
1242 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001243 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001244
Tim Peters026f8dc2004-08-19 16:38:58 +00001245 Examples from the docs:
1246
Guido van Rossum805365e2007-05-07 22:24:25 +00001247 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001248 [0, 1, ..., 18, 19]
1249
Guido van Rossum805365e2007-05-07 22:24:25 +00001250 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001251 ... # doctest: +NORMALIZE_WHITESPACE
1252 [0, 1, ..., 18, 19]
1253
Thomas Wouters477c8d52006-05-27 19:21:47 +00001254The SKIP flag causes an example to be skipped entirely. I.e., the
1255example is not run. It can be useful in contexts where doctest
1256examples serve as both documentation and test cases, and an example
1257should be included for documentation purposes, but should not be
1258checked (e.g., because its output is random, or depends on resources
1259which would be unavailable.) The SKIP flag can also be used for
1260'commenting out' broken examples.
1261
1262 >>> import unavailable_resource # doctest: +SKIP
1263 >>> unavailable_resource.do_something() # doctest: +SKIP
1264 >>> unavailable_resource.blow_up() # doctest: +SKIP
1265 Traceback (most recent call last):
1266 ...
1267 UncheckedBlowUpError: Nobody checks me.
1268
1269 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001270 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001271 0.721216923889
1272
Edward Loper71f55af2004-08-26 01:41:51 +00001273The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001274and actual outputs to be displayed using a unified diff:
1275
1276 >>> def f(x):
1277 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001278 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001279 ... a
1280 ... B
1281 ... c
1282 ... d
1283 ... f
1284 ... g
1285 ... h
1286 ... '''
1287
1288 >>> # Without the flag:
1289 >>> test = doctest.DocTestFinder().find(f)[0]
1290 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001291 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001292 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001293 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001294 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001295 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001296 Expected:
1297 a
1298 B
1299 c
1300 d
1301 f
1302 g
1303 h
1304 Got:
1305 a
1306 b
1307 c
1308 d
1309 e
1310 f
1311 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001312 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001313
1314 >>> # With the flag:
1315 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001316 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001317 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).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'))
Edward Loper56629292004-08-26 01:31:56 +00001323 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001324 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001325 a
1326 -B
1327 +b
1328 c
1329 d
1330 +e
1331 f
1332 g
1333 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001334 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001335
Edward Loper71f55af2004-08-26 01:41:51 +00001336The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001337and actual outputs to be displayed using a context diff:
1338
Edward Loper71f55af2004-08-26 01:41:51 +00001339 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001340 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001341 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001342 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001343 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001344 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001345 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001346 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001347 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001348 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001349 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001350 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001351 a
1352 ! B
1353 c
1354 d
1355 f
1356 g
1357 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001358 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001359 a
1360 ! b
1361 c
1362 d
1363 + e
1364 f
1365 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001366 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001367
1368
Edward Loper71f55af2004-08-26 01:41:51 +00001369The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001370used by the popular ndiff.py utility. This does intraline difference
1371marking, as well as interline differences.
1372
1373 >>> def f(x):
1374 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001375 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001376 ... a b c d e f g h i j k 1 m
1377 ... '''
1378 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001379 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001380 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001381 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001382 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001383 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001384 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001385 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001386 Differences (ndiff with -expected +actual):
1387 - a b c d e f g h i j k 1 m
1388 ? ^
1389 + a b c d e f g h i j k l m
1390 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001391 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001392
Ezio Melotti13925002011-03-16 11:05:33 +02001393The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001394failing example:
1395
1396 >>> def f(x):
1397 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001398 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001399 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001400 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001401 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001402 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001403 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001404 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001405 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001406 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001407 ... 500
1408 ... '''
1409 >>> test = doctest.DocTestFinder().find(f)[0]
1410 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1411 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001412 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001413 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001414 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001415 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001416 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001417 Expected:
1418 200
1419 Got:
1420 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001421 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001422
Ezio Melotti13925002011-03-16 11:05:33 +02001423However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001424
1425 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001426 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001427 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001428 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001429 Expecting:
1430 1
1431 ok
1432 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001433 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001434 Expecting:
1435 200
1436 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001437 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001438 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001439 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001440 Expected:
1441 200
1442 Got:
1443 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001444 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001445
R David Murray5a9d7062012-11-21 15:09:21 -05001446The FAIL_FAST flag causes the runner to exit after the first failing example,
1447so subsequent examples are not even attempted:
1448
1449 >>> flags = doctest.FAIL_FAST
1450 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1451 ... # doctest: +ELLIPSIS
1452 **********************************************************************
1453 File ..., line 5, in f
1454 Failed example:
1455 print(2) # first failure
1456 Expected:
1457 200
1458 Got:
1459 2
1460 TestResults(failed=1, attempted=2)
1461
1462Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1463FAIL_FAST only:
1464
1465 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1466 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1467 ... # doctest: +ELLIPSIS
1468 **********************************************************************
1469 File ..., line 5, in f
1470 Failed example:
1471 print(2) # first failure
1472 Expected:
1473 200
1474 Got:
1475 2
1476 TestResults(failed=1, attempted=2)
1477
1478For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1479exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001480
1481 >>> def f(x):
1482 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001483 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001484 ... 1
1485 ... >>> raise ValueError(2) # first failure
1486 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001487 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001488 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001489 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001490 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001491 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001492 ... 500
1493 ... '''
1494 >>> test = doctest.DocTestFinder().find(f)[0]
1495 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1496 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1497 ... # doctest: +ELLIPSIS
1498 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001499 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001500 Failed example:
1501 raise ValueError(2) # first failure
1502 Exception raised:
1503 ...
1504 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001505 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001506 >>> flags = doctest.FAIL_FAST
1507 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1508 ... # doctest: +ELLIPSIS
1509 **********************************************************************
1510 File ..., line 5, in f
1511 Failed example:
1512 raise ValueError(2) # first failure
1513 Exception raised:
1514 ...
1515 ValueError: 2
1516 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001517
Thomas Wouters477c8d52006-05-27 19:21:47 +00001518New option flags can also be registered, via register_optionflag(). Here
1519we reach into doctest's internals a bit.
1520
1521 >>> unlikely = "UNLIKELY_OPTION_NAME"
1522 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1523 False
1524 >>> new_flag_value = doctest.register_optionflag(unlikely)
1525 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1526 True
1527
1528Before 2.4.4/2.5, registering a name more than once erroneously created
1529more than one flag value. Here we verify that's fixed:
1530
1531 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1532 >>> redundant_flag_value == new_flag_value
1533 True
1534
1535Clean up.
1536 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1537
Tim Petersc6cbab02004-08-22 19:43:28 +00001538 """
1539
Tim Peters8485b562004-08-04 18:46:34 +00001540 def option_directives(): r"""
1541Tests of `DocTestRunner`'s option directive mechanism.
1542
Edward Loper74bca7a2004-08-12 02:27:44 +00001543Option directives can be used to turn option flags on or off for a
1544single example. To turn an option on for an example, follow that
1545example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001546
1547 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001548 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001549 ... [0, 1, ..., 9]
1550 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001551 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001552 ... [0, 1, ..., 9]
1553 ... '''
1554 >>> test = doctest.DocTestFinder().find(f)[0]
1555 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001556 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001557 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001558 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001559 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001560 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001561 Expected:
1562 [0, 1, ..., 9]
1563 Got:
1564 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001565 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001566
1567To turn an option off for an example, follow that example with a
1568comment of the form ``# doctest: -OPTION``:
1569
1570 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001571 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001572 ... [0, 1, ..., 9]
1573 ...
1574 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001575 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001576 ... [0, 1, ..., 9]
1577 ... '''
1578 >>> test = doctest.DocTestFinder().find(f)[0]
1579 >>> doctest.DocTestRunner(verbose=False,
1580 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001581 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001582 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001583 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001584 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001585 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001586 Expected:
1587 [0, 1, ..., 9]
1588 Got:
1589 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001590 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001591
1592Option directives affect only the example that they appear with; they
1593do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001594
Edward Loper74bca7a2004-08-12 02:27:44 +00001595 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001596 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001597 ... [0, 1, ..., 9]
1598 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001599 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001600 ... [0, 1, ..., 9]
1601 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001602 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001603 ... [0, 1, ..., 9]
1604 ... '''
1605 >>> test = doctest.DocTestFinder().find(f)[0]
1606 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001607 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001608 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001609 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001610 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001611 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001612 Expected:
1613 [0, 1, ..., 9]
1614 Got:
1615 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001616 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001617 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001618 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001619 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001620 Expected:
1621 [0, 1, ..., 9]
1622 Got:
1623 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001624 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001625
Edward Loper74bca7a2004-08-12 02:27:44 +00001626Multiple options may be modified by a single option directive. They
1627may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001628
1629 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001630 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001631 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001632 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001633 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001634 ... [0, 1, ..., 9]
1635 ... '''
1636 >>> test = doctest.DocTestFinder().find(f)[0]
1637 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001638 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001639 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001640 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001641 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001642 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001643 Expected:
1644 [0, 1, ..., 9]
1645 Got:
1646 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001647 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001648
1649 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001650 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001651 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001652 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001653 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1654 ... [0, 1, ..., 9]
1655 ... '''
1656 >>> test = doctest.DocTestFinder().find(f)[0]
1657 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001658 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001659 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001660 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001661 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001662 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001663 Expected:
1664 [0, 1, ..., 9]
1665 Got:
1666 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001667 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001668
1669 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001670 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001671 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001672 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001673 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1674 ... [0, 1, ..., 9]
1675 ... '''
1676 >>> test = doctest.DocTestFinder().find(f)[0]
1677 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001678 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001679 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001680 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001681 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001682 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001683 Expected:
1684 [0, 1, ..., 9]
1685 Got:
1686 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001687 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001688
1689The option directive may be put on the line following the source, as
1690long as a continuation prompt is used:
1691
1692 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001693 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001694 ... ... # doctest: +ELLIPSIS
1695 ... [0, 1, ..., 9]
1696 ... '''
1697 >>> test = doctest.DocTestFinder().find(f)[0]
1698 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001699 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001700
Edward Loper74bca7a2004-08-12 02:27:44 +00001701For examples with multi-line source, the option directive may appear
1702at the end of any line:
1703
1704 >>> def f(x): r'''
1705 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001706 ... ... print(' ', x, end='', sep='')
1707 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001708 ...
1709 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001710 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1711 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001712 ... '''
1713 >>> test = doctest.DocTestFinder().find(f)[0]
1714 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001715 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001716
1717If more than one line of an example with multi-line source has an
1718option directive, then they are combined:
1719
1720 >>> def f(x): r'''
1721 ... Should fail (option directive not on the last line):
1722 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001723 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001724 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001725 ... '''
1726 >>> test = doctest.DocTestFinder().find(f)[0]
1727 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001728 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001729
1730It is an error to have a comment of the form ``# doctest:`` that is
1731*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1732``OPTION`` is an option that has been registered with
1733`register_option`:
1734
1735 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001736 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001737 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1738 Traceback (most recent call last):
1739 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1740
1741 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001742 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001743 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1744 Traceback (most recent call last):
1745 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1746
1747It is an error to use an option directive on a line that contains no
1748source:
1749
1750 >>> s = '>>> # doctest: +ELLIPSIS'
1751 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1752 Traceback (most recent call last):
1753 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 +00001754"""
1755
1756def test_testsource(): r"""
1757Unit tests for `testsource()`.
1758
1759The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001760test with that name in that module, and converts it to a script. The
1761example code is converted to regular Python code. The surrounding
1762words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001763
1764 >>> import test.test_doctest
1765 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001766 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001767 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001768 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001769 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001770 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001771 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001772 #
Edward Lopera5db6002004-08-12 02:41:30 +00001773 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001774 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001775
1776 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001777 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001778 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001779 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001780 ## 1
1781 ## 2
1782 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001783 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001784
1785 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001786 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001787 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001788 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001789 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001790 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001791 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001792 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001793 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001794"""
1795
1796def test_debug(): r"""
1797
1798Create a docstring that we want to debug:
1799
1800 >>> s = '''
1801 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001802 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001803 ... 12
1804 ... '''
1805
1806Create some fake stdin input, to feed to the debugger:
1807
Tim Peters8485b562004-08-04 18:46:34 +00001808 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001809 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001810
1811Run the debugger on the docstring, and then restore sys.stdin.
1812
Edward Loper2de91ba2004-08-27 02:07:46 +00001813 >>> try: doctest.debug_src(s)
1814 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001815 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001816 (Pdb) next
1817 12
Tim Peters8485b562004-08-04 18:46:34 +00001818 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001820 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001821 12
1822 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001823
1824"""
1825
Brett Cannon31f59292011-02-21 19:29:56 +00001826if not hasattr(sys, 'gettrace') or not sys.gettrace():
1827 def test_pdb_set_trace():
1828 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001829
Brett Cannon31f59292011-02-21 19:29:56 +00001830 You can use pdb.set_trace from a doctest. To do so, you must
1831 retrieve the set_trace function from the pdb module at the time
1832 you use it. The doctest module changes sys.stdout so that it can
1833 capture program output. It also temporarily replaces pdb.set_trace
1834 with a version that restores stdout. This is necessary for you to
1835 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001836
Brett Cannon31f59292011-02-21 19:29:56 +00001837 >>> doc = '''
1838 ... >>> x = 42
1839 ... >>> raise Exception('clé')
1840 ... Traceback (most recent call last):
1841 ... Exception: clé
1842 ... >>> import pdb; pdb.set_trace()
1843 ... '''
1844 >>> parser = doctest.DocTestParser()
1845 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1846 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001847
Brett Cannon31f59292011-02-21 19:29:56 +00001848 To demonstrate this, we'll create a fake standard input that
1849 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001850
Brett Cannon31f59292011-02-21 19:29:56 +00001851 >>> import tempfile
1852 >>> real_stdin = sys.stdin
1853 >>> sys.stdin = _FakeInput([
1854 ... 'print(x)', # print data defined by the example
1855 ... 'continue', # stop debugging
1856 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001857
Brett Cannon31f59292011-02-21 19:29:56 +00001858 >>> try: runner.run(test)
1859 ... finally: sys.stdin = real_stdin
1860 --Return--
1861 > <doctest foo-bar@baz[2]>(1)<module>()->None
1862 -> import pdb; pdb.set_trace()
1863 (Pdb) print(x)
1864 42
1865 (Pdb) continue
1866 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001867
Brett Cannon31f59292011-02-21 19:29:56 +00001868 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001869
Brett Cannon31f59292011-02-21 19:29:56 +00001870 >>> def calls_set_trace():
1871 ... y=2
1872 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001873
Brett Cannon31f59292011-02-21 19:29:56 +00001874 >>> doc = '''
1875 ... >>> x=1
1876 ... >>> calls_set_trace()
1877 ... '''
1878 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1879 >>> real_stdin = sys.stdin
1880 >>> sys.stdin = _FakeInput([
1881 ... 'print(y)', # print data defined in the function
1882 ... 'up', # out of function
1883 ... 'print(x)', # print data defined by the example
1884 ... 'continue', # stop debugging
1885 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001886
Brett Cannon31f59292011-02-21 19:29:56 +00001887 >>> try:
1888 ... runner.run(test)
1889 ... finally:
1890 ... sys.stdin = real_stdin
1891 --Return--
1892 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1893 -> import pdb; pdb.set_trace()
1894 (Pdb) print(y)
1895 2
1896 (Pdb) up
1897 > <doctest foo-bar@baz[1]>(1)<module>()
1898 -> calls_set_trace()
1899 (Pdb) print(x)
1900 1
1901 (Pdb) continue
1902 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001903
Brett Cannon31f59292011-02-21 19:29:56 +00001904 During interactive debugging, source code is shown, even for
1905 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001906
Brett Cannon31f59292011-02-21 19:29:56 +00001907 >>> doc = '''
1908 ... >>> def f(x):
1909 ... ... g(x*2)
1910 ... >>> def g(x):
1911 ... ... print(x+3)
1912 ... ... import pdb; pdb.set_trace()
1913 ... >>> f(3)
1914 ... '''
1915 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1916 >>> real_stdin = sys.stdin
1917 >>> sys.stdin = _FakeInput([
1918 ... 'list', # list source from example 2
1919 ... 'next', # return from g()
1920 ... 'list', # list source from example 1
1921 ... 'next', # return from f()
1922 ... 'list', # list source from example 3
1923 ... 'continue', # stop debugging
1924 ... ''])
1925 >>> try: runner.run(test)
1926 ... finally: sys.stdin = real_stdin
1927 ... # doctest: +NORMALIZE_WHITESPACE
1928 --Return--
1929 > <doctest foo-bar@baz[1]>(3)g()->None
1930 -> import pdb; pdb.set_trace()
1931 (Pdb) list
1932 1 def g(x):
1933 2 print(x+3)
1934 3 -> import pdb; pdb.set_trace()
1935 [EOF]
1936 (Pdb) next
1937 --Return--
1938 > <doctest foo-bar@baz[0]>(2)f()->None
1939 -> g(x*2)
1940 (Pdb) list
1941 1 def f(x):
1942 2 -> g(x*2)
1943 [EOF]
1944 (Pdb) next
1945 --Return--
1946 > <doctest foo-bar@baz[2]>(1)<module>()->None
1947 -> f(3)
1948 (Pdb) list
1949 1 -> f(3)
1950 [EOF]
1951 (Pdb) continue
1952 **********************************************************************
1953 File "foo-bar@baz.py", line 7, in foo-bar@baz
1954 Failed example:
1955 f(3)
1956 Expected nothing
1957 Got:
1958 9
1959 TestResults(failed=1, attempted=3)
1960 """
Jim Fulton356fd192004-08-09 11:34:47 +00001961
Brett Cannon31f59292011-02-21 19:29:56 +00001962 def test_pdb_set_trace_nested():
1963 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00001964
Brett Cannon31f59292011-02-21 19:29:56 +00001965 >>> class C(object):
1966 ... def calls_set_trace(self):
1967 ... y = 1
1968 ... import pdb; pdb.set_trace()
1969 ... self.f1()
1970 ... y = 2
1971 ... def f1(self):
1972 ... x = 1
1973 ... self.f2()
1974 ... x = 2
1975 ... def f2(self):
1976 ... z = 1
1977 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00001978
Brett Cannon31f59292011-02-21 19:29:56 +00001979 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00001980
Brett Cannon31f59292011-02-21 19:29:56 +00001981 >>> doc = '''
1982 ... >>> a = 1
1983 ... >>> calls_set_trace()
1984 ... '''
1985 >>> parser = doctest.DocTestParser()
1986 >>> runner = doctest.DocTestRunner(verbose=False)
1987 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1988 >>> real_stdin = sys.stdin
1989 >>> sys.stdin = _FakeInput([
1990 ... 'print(y)', # print data defined in the function
1991 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1992 ... 'up', 'print(x)',
1993 ... 'up', 'print(y)',
1994 ... 'up', 'print(foo)',
1995 ... 'continue', # stop debugging
1996 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00001997
Brett Cannon31f59292011-02-21 19:29:56 +00001998 >>> try:
1999 ... runner.run(test)
2000 ... finally:
2001 ... sys.stdin = real_stdin
2002 ... # doctest: +REPORT_NDIFF
2003 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2004 -> self.f1()
2005 (Pdb) print(y)
2006 1
2007 (Pdb) step
2008 --Call--
2009 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2010 -> def f1(self):
2011 (Pdb) step
2012 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2013 -> x = 1
2014 (Pdb) step
2015 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2016 -> self.f2()
2017 (Pdb) step
2018 --Call--
2019 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2020 -> def f2(self):
2021 (Pdb) step
2022 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2023 -> z = 1
2024 (Pdb) step
2025 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2026 -> z = 2
2027 (Pdb) print(z)
2028 1
2029 (Pdb) up
2030 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2031 -> self.f2()
2032 (Pdb) print(x)
2033 1
2034 (Pdb) up
2035 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2036 -> self.f1()
2037 (Pdb) print(y)
2038 1
2039 (Pdb) up
2040 > <doctest foo-bar@baz[1]>(1)<module>()
2041 -> calls_set_trace()
2042 (Pdb) print(foo)
2043 *** NameError: name 'foo' is not defined
2044 (Pdb) continue
2045 TestResults(failed=0, attempted=2)
2046 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002047
Tim Peters19397e52004-08-06 22:02:59 +00002048def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002049 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002050
2051 We create a Suite by providing a module. A module can be provided
2052 by passing a module object:
2053
2054 >>> import unittest
2055 >>> import test.sample_doctest
2056 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2057 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002058 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002059
2060 We can also supply the module by name:
2061
2062 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2063 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002064 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002065
R David Murray5abd76a2012-09-10 10:15:58 -04002066 The module need not contain any doctest examples:
2067
2068 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2069 >>> suite.run(unittest.TestResult())
2070 <unittest.result.TestResult run=0 errors=0 failures=0>
2071
2072 However, if DocTestSuite finds no docstrings, it raises an error:
2073
2074 >>> try:
2075 ... doctest.DocTestSuite('test.sample_doctest_no_docstrings')
2076 ... except ValueError as e:
2077 ... error = e
2078
2079 >>> print(error.args[1])
2080 has no docstrings
2081
2082 You can prevent this error by passing a DocTestFinder instance with
2083 the `exclude_empty` keyword argument set to False:
2084
2085 >>> finder = doctest.DocTestFinder(exclude_empty=False)
2086 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2087 ... test_finder=finder)
2088 >>> suite.run(unittest.TestResult())
2089 <unittest.result.TestResult run=0 errors=0 failures=0>
2090
Tim Peters19397e52004-08-06 22:02:59 +00002091 We can use the current module:
2092
2093 >>> suite = test.sample_doctest.test_suite()
2094 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002095 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002096
2097 We can supply global variables. If we pass globs, they will be
2098 used instead of the module globals. Here we'll pass an empty
2099 globals, triggering an extra error:
2100
2101 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2102 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002103 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002104
2105 Alternatively, we can provide extra globals. Here we'll make an
2106 error go away by providing an extra global variable:
2107
2108 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2109 ... extraglobs={'y': 1})
2110 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002111 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002112
2113 You can pass option flags. Here we'll cause an extra error
2114 by disabling the blank-line feature:
2115
2116 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002117 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002118 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002119 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002120
Tim Peters1e277ee2004-08-07 05:37:52 +00002121 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002122
Jim Fultonf54bad42004-08-28 14:57:56 +00002123 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002124 ... import test.test_doctest
2125 ... test.test_doctest.sillySetup = True
2126
Jim Fultonf54bad42004-08-28 14:57:56 +00002127 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002128 ... import test.test_doctest
2129 ... del test.test_doctest.sillySetup
2130
2131 Here, we installed a silly variable that the test expects:
2132
2133 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2134 ... setUp=setUp, tearDown=tearDown)
2135 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002136 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002137
2138 But the tearDown restores sanity:
2139
2140 >>> import test.test_doctest
2141 >>> test.test_doctest.sillySetup
2142 Traceback (most recent call last):
2143 ...
2144 AttributeError: 'module' object has no attribute 'sillySetup'
2145
Jim Fultonf54bad42004-08-28 14:57:56 +00002146 The setUp and tearDown funtions are passed test objects. Here
2147 we'll use the setUp function to supply the missing variable y:
2148
2149 >>> def setUp(test):
2150 ... test.globs['y'] = 1
2151
2152 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2153 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002154 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002155
2156 Here, we didn't need to use a tearDown function because we
2157 modified the test globals, which are a copy of the
2158 sample_doctest module dictionary. The test globals are
2159 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002160 """
2161
2162def test_DocFileSuite():
2163 """We can test tests found in text files using a DocFileSuite.
2164
2165 We create a suite by providing the names of one or more text
2166 files that include examples:
2167
2168 >>> import unittest
2169 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002170 ... 'test_doctest2.txt',
2171 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002172 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002173 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002174
2175 The test files are looked for in the directory containing the
2176 calling module. A package keyword argument can be provided to
2177 specify a different relative location.
2178
2179 >>> import unittest
2180 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2181 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002182 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002183 ... package='test')
2184 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002185 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002186
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002187 Support for using a package's __loader__.get_data() is also
2188 provided.
2189
2190 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002191 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002192 >>> if not hasattr(test, '__loader__'):
2193 ... test.__loader__ = pkgutil.get_loader(test)
2194 ... added_loader = True
2195 >>> try:
2196 ... suite = doctest.DocFileSuite('test_doctest.txt',
2197 ... 'test_doctest2.txt',
2198 ... 'test_doctest4.txt',
2199 ... package='test')
2200 ... suite.run(unittest.TestResult())
2201 ... finally:
2202 ... if added_loader:
2203 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002204 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002205
Edward Loper0273f5b2004-09-18 20:27:04 +00002206 '/' should be used as a path separator. It will be converted
2207 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002208
2209 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2210 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002211 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002212
Edward Loper0273f5b2004-09-18 20:27:04 +00002213 If DocFileSuite is used from an interactive session, then files
2214 are resolved relative to the directory of sys.argv[0]:
2215
Christian Heimes45f9af32007-11-27 21:50:00 +00002216 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002217 >>> save_argv = sys.argv
2218 >>> sys.argv = [test.test_doctest.__file__]
2219 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002220 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002221 >>> sys.argv = save_argv
2222
Edward Loper052d0cd2004-09-19 17:19:33 +00002223 By setting `module_relative=False`, os-specific paths may be
2224 used (including absolute paths and paths relative to the
2225 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002226
2227 >>> # Get the absolute path of the test package.
2228 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2229 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2230
2231 >>> # Use it to find the absolute path of test_doctest.txt.
2232 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2233
Edward Loper052d0cd2004-09-19 17:19:33 +00002234 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002235 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002236 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002237
Edward Loper052d0cd2004-09-19 17:19:33 +00002238 It is an error to specify `package` when `module_relative=False`:
2239
2240 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2241 ... package='test')
2242 Traceback (most recent call last):
2243 ValueError: Package may only be specified for module-relative paths.
2244
Tim Peters19397e52004-08-06 22:02:59 +00002245 You can specify initial global variables:
2246
2247 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2248 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002249 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002250 ... globs={'favorite_color': 'blue'})
2251 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002252 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002253
2254 In this case, we supplied a missing favorite color. You can
2255 provide doctest options:
2256
2257 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2258 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002259 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002260 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2261 ... globs={'favorite_color': 'blue'})
2262 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002263 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002264
2265 And, you can provide setUp and tearDown functions:
2266
Jim Fultonf54bad42004-08-28 14:57:56 +00002267 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002268 ... import test.test_doctest
2269 ... test.test_doctest.sillySetup = True
2270
Jim Fultonf54bad42004-08-28 14:57:56 +00002271 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002272 ... import test.test_doctest
2273 ... del test.test_doctest.sillySetup
2274
2275 Here, we installed a silly variable that the test expects:
2276
2277 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2278 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002279 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002280 ... setUp=setUp, tearDown=tearDown)
2281 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002282 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002283
2284 But the tearDown restores sanity:
2285
2286 >>> import test.test_doctest
2287 >>> test.test_doctest.sillySetup
2288 Traceback (most recent call last):
2289 ...
2290 AttributeError: 'module' object has no attribute 'sillySetup'
2291
Jim Fultonf54bad42004-08-28 14:57:56 +00002292 The setUp and tearDown funtions are passed test objects.
2293 Here, we'll use a setUp function to set the favorite color in
2294 test_doctest.txt:
2295
2296 >>> def setUp(test):
2297 ... test.globs['favorite_color'] = 'blue'
2298
2299 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2300 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002301 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002302
2303 Here, we didn't need to use a tearDown function because we
2304 modified the test globals. The test globals are
2305 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002306
Fred Drake7c404a42004-12-21 23:46:34 +00002307 Tests in a file run using `DocFileSuite` can also access the
2308 `__file__` global, which is set to the name of the file
2309 containing the tests:
2310
2311 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2312 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002313 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002314
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002315 If the tests contain non-ASCII characters, we have to specify which
2316 encoding the file is encoded with. We do so by using the `encoding`
2317 parameter:
2318
2319 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2320 ... 'test_doctest2.txt',
2321 ... 'test_doctest4.txt',
2322 ... encoding='utf-8')
2323 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002324 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002325
Jim Fultonf54bad42004-08-28 14:57:56 +00002326 """
Tim Peters19397e52004-08-06 22:02:59 +00002327
Jim Fulton07a349c2004-08-22 14:10:00 +00002328def test_trailing_space_in_test():
2329 """
Tim Petersa7def722004-08-23 22:13:22 +00002330 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002331
Jim Fulton07a349c2004-08-22 14:10:00 +00002332 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002333 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002334 foo \n
2335 """
Tim Peters19397e52004-08-06 22:02:59 +00002336
Jim Fultonf54bad42004-08-28 14:57:56 +00002337
2338def test_unittest_reportflags():
2339 """Default unittest reporting flags can be set to control reporting
2340
2341 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2342 only the first failure of each test. First, we'll look at the
2343 output without the flag. The file test_doctest.txt file has two
2344 tests. They both fail if blank lines are disabled:
2345
2346 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2347 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2348 >>> import unittest
2349 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002350 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002351 Traceback ...
2352 Failed example:
2353 favorite_color
2354 ...
2355 Failed example:
2356 if 1:
2357 ...
2358
2359 Note that we see both failures displayed.
2360
2361 >>> old = doctest.set_unittest_reportflags(
2362 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2363
2364 Now, when we run the test:
2365
2366 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002367 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002368 Traceback ...
2369 Failed example:
2370 favorite_color
2371 Exception raised:
2372 ...
2373 NameError: name 'favorite_color' is not defined
2374 <BLANKLINE>
2375 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002376
Jim Fultonf54bad42004-08-28 14:57:56 +00002377 We get only the first failure.
2378
2379 If we give any reporting options when we set up the tests,
2380 however:
2381
2382 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2383 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2384
2385 Then the default eporting options are ignored:
2386
2387 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002388 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002389 Traceback ...
2390 Failed example:
2391 favorite_color
2392 ...
2393 Failed example:
2394 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002395 print('a')
2396 print()
2397 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002398 Differences (ndiff with -expected +actual):
2399 a
2400 - <BLANKLINE>
2401 +
2402 b
2403 <BLANKLINE>
2404 <BLANKLINE>
2405
2406
2407 Test runners can restore the formatting flags after they run:
2408
2409 >>> ignored = doctest.set_unittest_reportflags(old)
2410
2411 """
2412
Edward Loper052d0cd2004-09-19 17:19:33 +00002413def test_testfile(): r"""
2414Tests for the `testfile()` function. This function runs all the
2415doctest examples in a given file. In its simple invokation, it is
2416called with the name of a file, which is taken to be relative to the
2417calling module. The return value is (#failures, #tests).
2418
Florent Xicluna59250852010-02-27 14:21:57 +00002419We don't want `-v` in sys.argv for these tests.
2420
2421 >>> save_argv = sys.argv
2422 >>> if '-v' in sys.argv:
2423 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2424
2425
Edward Loper052d0cd2004-09-19 17:19:33 +00002426 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2427 **********************************************************************
2428 File "...", line 6, in test_doctest.txt
2429 Failed example:
2430 favorite_color
2431 Exception raised:
2432 ...
2433 NameError: name 'favorite_color' is not defined
2434 **********************************************************************
2435 1 items had failures:
2436 1 of 2 in test_doctest.txt
2437 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002438 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002439 >>> doctest.master = None # Reset master.
2440
2441(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002442`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002443same name.)
2444
2445Globals may be specified with the `globs` and `extraglobs` parameters:
2446
2447 >>> globs = {'favorite_color': 'blue'}
2448 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002449 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002450 >>> doctest.master = None # Reset master.
2451
2452 >>> extraglobs = {'favorite_color': 'red'}
2453 >>> doctest.testfile('test_doctest.txt', globs=globs,
2454 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2455 **********************************************************************
2456 File "...", line 6, in test_doctest.txt
2457 Failed example:
2458 favorite_color
2459 Expected:
2460 'blue'
2461 Got:
2462 'red'
2463 **********************************************************************
2464 1 items had failures:
2465 1 of 2 in test_doctest.txt
2466 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002467 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002468 >>> doctest.master = None # Reset master.
2469
2470The file may be made relative to a given module or package, using the
2471optional `module_relative` parameter:
2472
2473 >>> doctest.testfile('test_doctest.txt', globs=globs,
2474 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002475 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002476 >>> doctest.master = None # Reset master.
2477
Ezio Melotti13925002011-03-16 11:05:33 +02002478Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002479
2480 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2481 Trying:
2482 favorite_color
2483 Expecting:
2484 'blue'
2485 ok
2486 Trying:
2487 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002488 print('a')
2489 print()
2490 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002491 Expecting:
2492 a
2493 <BLANKLINE>
2494 b
2495 ok
2496 1 items passed all tests:
2497 2 tests in test_doctest.txt
2498 2 tests in 1 items.
2499 2 passed and 0 failed.
2500 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002501 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002502 >>> doctest.master = None # Reset master.
2503
2504The name of the test may be specified with the optional `name`
2505parameter:
2506
2507 >>> doctest.testfile('test_doctest.txt', name='newname')
2508 ... # doctest: +ELLIPSIS
2509 **********************************************************************
2510 File "...", line 6, in newname
2511 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002512 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002513 >>> doctest.master = None # Reset master.
2514
Ezio Melotti13925002011-03-16 11:05:33 +02002515The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002516parameter:
2517
2518 >>> doctest.testfile('test_doctest.txt', report=False)
2519 ... # doctest: +ELLIPSIS
2520 **********************************************************************
2521 File "...", line 6, in test_doctest.txt
2522 Failed example:
2523 favorite_color
2524 Exception raised:
2525 ...
2526 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002527 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002528 >>> doctest.master = None # Reset master.
2529
2530The optional keyword argument `raise_on_error` can be used to raise an
2531exception on the first error (which may be useful for postmortem
2532debugging):
2533
2534 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2535 ... # doctest: +ELLIPSIS
2536 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002537 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002538 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002539
2540If the tests contain non-ASCII characters, the tests might fail, since
2541it's unknown which encoding is used. The encoding can be specified
2542using the optional keyword argument `encoding`:
2543
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002544 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002545 **********************************************************************
2546 File "...", line 7, in test_doctest4.txt
2547 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002548 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002549 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002550 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002551 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002552 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002553 **********************************************************************
2554 ...
2555 **********************************************************************
2556 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002557 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002558 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002559 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002560 >>> doctest.master = None # Reset master.
2561
2562 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002563 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002564 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002565
2566Test the verbose output:
2567
2568 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2569 Trying:
2570 'föö'
2571 Expecting:
2572 'f\xf6\xf6'
2573 ok
2574 Trying:
2575 'bÄ…r'
2576 Expecting:
2577 'b\u0105r'
2578 ok
2579 1 items passed all tests:
2580 2 tests in test_doctest4.txt
2581 2 tests in 1 items.
2582 2 passed and 0 failed.
2583 Test passed.
2584 TestResults(failed=0, attempted=2)
2585 >>> doctest.master = None # Reset master.
2586 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002587"""
2588
R. David Murray58641de2009-06-12 15:33:19 +00002589def test_testmod(): r"""
2590Tests for the testmod function. More might be useful, but for now we're just
2591testing the case raised by Issue 6195, where trying to doctest a C module would
2592fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2593out of the binary module.
2594
2595 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002596 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002597 TestResults(failed=0, attempted=0)
2598"""
2599
Victor Stinner9d396392010-10-16 21:54:59 +00002600try:
2601 os.fsencode("foo-bär@baz.py")
2602except UnicodeEncodeError:
2603 # Skip the test: the filesystem encoding is unable to encode the filename
2604 pass
2605else:
2606 def test_unicode(): """
2607Check doctest with a non-ascii filename:
2608
2609 >>> doc = '''
2610 ... >>> raise Exception('clé')
2611 ... '''
2612 ...
2613 >>> parser = doctest.DocTestParser()
2614 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2615 >>> test
2616 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2617 >>> runner = doctest.DocTestRunner(verbose=False)
2618 >>> runner.run(test) # doctest: +ELLIPSIS
2619 **********************************************************************
2620 File "foo-bär@baz.py", line 2, in foo-bär@baz
2621 Failed example:
2622 raise Exception('clé')
2623 Exception raised:
2624 Traceback (most recent call last):
2625 File ...
2626 compileflags, 1), test.globs)
2627 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2628 raise Exception('clé')
2629 Exception: clé
2630 TestResults(failed=1, attempted=1)
2631 """
2632
R David Murray5707d502013-06-23 14:24:13 -04002633def test_CLI(): r"""
2634The doctest module can be used to run doctests against an arbitrary file.
2635These tests test this CLI functionality.
2636
2637We'll use the support module's script_helpers for this, and write a test files
R David Murray4af68982013-06-25 08:11:22 -04002638to a temp dir to run the command against. Due to a current limitation in
2639script_helpers, though, we need a little utility function to turn the returned
2640output into something we can doctest against:
R David Murray5707d502013-06-23 14:24:13 -04002641
R David Murray4af68982013-06-25 08:11:22 -04002642 >>> def normalize(s):
2643 ... return '\n'.join(s.decode().splitlines())
2644
2645Note: we also pass TERM='' to all the assert_python calls to avoid a bug
2646in the readline library that is triggered in these tests because we are
2647running them in a new python process. See:
2648
2649 http://lists.gnu.org/archive/html/bug-readline/2013-06/msg00000.html
2650
2651With those preliminaries out of the way, we'll start with a file with two
2652simple tests and no errors. We'll run both the unadorned doctest command, and
2653the verbose version, and then check the output:
R David Murray5707d502013-06-23 14:24:13 -04002654
2655 >>> from test import script_helper
2656 >>> with script_helper.temp_dir() as tmpdir:
2657 ... fn = os.path.join(tmpdir, 'myfile.doc')
2658 ... with open(fn, 'w') as f:
2659 ... _ = f.write('This is a very simple test file.\n')
2660 ... _ = f.write(' >>> 1 + 1\n')
2661 ... _ = f.write(' 2\n')
2662 ... _ = f.write(' >>> "a"\n')
2663 ... _ = f.write(" 'a'\n")
2664 ... _ = f.write('\n')
2665 ... _ = f.write('And that is it.\n')
2666 ... rc1, out1, err1 = script_helper.assert_python_ok(
R David Murray4af68982013-06-25 08:11:22 -04002667 ... '-m', 'doctest', fn, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002668 ... rc2, out2, err2 = script_helper.assert_python_ok(
R David Murray4af68982013-06-25 08:11:22 -04002669 ... '-m', 'doctest', '-v', fn, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002670
2671With no arguments and passing tests, we should get no output:
2672
2673 >>> rc1, out1, err1
2674 (0, b'', b'')
2675
2676With the verbose flag, we should see the test output, but no error output:
2677
2678 >>> rc2, err2
2679 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002680 >>> print(normalize(out2))
R David Murray5707d502013-06-23 14:24:13 -04002681 Trying:
2682 1 + 1
2683 Expecting:
2684 2
2685 ok
2686 Trying:
2687 "a"
2688 Expecting:
2689 'a'
2690 ok
2691 1 items passed all tests:
2692 2 tests in myfile.doc
2693 2 tests in 1 items.
2694 2 passed and 0 failed.
2695 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002696
2697Now we'll write a couple files, one with three tests, the other a python module
2698with two tests, both of the files having "errors" in the tests that can be made
2699non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
2700the first file, NORMALIZE_WHITESPACE in the second). This combination will
2701allow to thoroughly test the -f and -o flags, as well as the doctest command's
2702ability to process more than one file on the command line and, since the second
2703file ends in '.py', its handling of python module files (as opposed to straight
2704text files).
2705
2706 >>> from test import script_helper
2707 >>> with script_helper.temp_dir() as tmpdir:
2708 ... fn = os.path.join(tmpdir, 'myfile.doc')
2709 ... with open(fn, 'w') as f:
2710 ... _ = f.write('This is another simple test file.\n')
2711 ... _ = f.write(' >>> 1 + 1\n')
2712 ... _ = f.write(' 2\n')
2713 ... _ = f.write(' >>> "abcdef"\n')
2714 ... _ = f.write(" 'a...f'\n")
2715 ... _ = f.write(' >>> "ajkml"\n')
2716 ... _ = f.write(" 'a...l'\n")
2717 ... _ = f.write('\n')
2718 ... _ = f.write('And that is it.\n')
2719 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
2720 ... with open(fn2, 'w') as f:
2721 ... _ = f.write('def test_func():\n')
2722 ... _ = f.write(' \"\"\"\n')
2723 ... _ = f.write(' This is simple python test function.\n')
2724 ... _ = f.write(' >>> 1 + 1\n')
2725 ... _ = f.write(' 2\n')
2726 ... _ = f.write(' >>> "abc def"\n')
2727 ... _ = f.write(" 'abc def'\n")
2728 ... _ = f.write("\n")
2729 ... _ = f.write(' \"\"\"\n')
2730 ... import shutil
2731 ... rc1, out1, err1 = script_helper.assert_python_failure(
R David Murray4af68982013-06-25 08:11:22 -04002732 ... '-m', 'doctest', fn, fn2, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002733 ... rc2, out2, err2 = script_helper.assert_python_ok(
R David Murray4af68982013-06-25 08:11:22 -04002734 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002735 ... rc3, out3, err3 = script_helper.assert_python_ok(
2736 ... '-m', 'doctest', '-o', 'ELLIPSIS',
R David Murray4af68982013-06-25 08:11:22 -04002737 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002738 ... rc4, out4, err4 = script_helper.assert_python_failure(
R David Murray4af68982013-06-25 08:11:22 -04002739 ... '-m', 'doctest', '-f', fn, fn2, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002740 ... rc5, out5, err5 = script_helper.assert_python_ok(
2741 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
R David Murray4af68982013-06-25 08:11:22 -04002742 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2, TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002743
2744Our first test run will show the errors from the first file (doctest stops if a
2745file has errors). Note that doctest test-run error output appears on stdout,
2746not stderr:
2747
2748 >>> rc1, err1
2749 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002750 >>> print(normalize(out1)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002751 **********************************************************************
2752 File "...myfile.doc", line 4, in myfile.doc
2753 Failed example:
2754 "abcdef"
2755 Expected:
2756 'a...f'
2757 Got:
2758 'abcdef'
2759 **********************************************************************
2760 File "...myfile.doc", line 6, in myfile.doc
2761 Failed example:
2762 "ajkml"
2763 Expected:
2764 'a...l'
2765 Got:
2766 'ajkml'
2767 **********************************************************************
2768 1 items had failures:
2769 2 of 3 in myfile.doc
2770 ***Test Failed*** 2 failures.
R David Murray5707d502013-06-23 14:24:13 -04002771
2772With -o ELLIPSIS specified, the second run, against just the first file, should
2773produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
2774should the third, which ran against both files:
2775
2776 >>> rc2, out2, err2
2777 (0, b'', b'')
2778 >>> rc3, out3, err3
2779 (0, b'', b'')
2780
2781The fourth run uses FAIL_FAST, so we should see only one error:
2782
2783 >>> rc4, err4
2784 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002785 >>> print(normalize(out4)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002786 **********************************************************************
2787 File "...myfile.doc", line 4, in myfile.doc
2788 Failed example:
2789 "abcdef"
2790 Expected:
2791 'a...f'
2792 Got:
2793 'abcdef'
2794 **********************************************************************
2795 1 items had failures:
2796 1 of 2 in myfile.doc
2797 ***Test Failed*** 1 failures.
R David Murray5707d502013-06-23 14:24:13 -04002798
2799The fifth test uses verbose with the two options, so we should get verbose
2800success output for the tests in both files:
2801
2802 >>> rc5, err5
2803 (0, b'')
R David Murray4af68982013-06-25 08:11:22 -04002804 >>> print(normalize(out5))
R David Murray5707d502013-06-23 14:24:13 -04002805 Trying:
2806 1 + 1
2807 Expecting:
2808 2
2809 ok
2810 Trying:
2811 "abcdef"
2812 Expecting:
2813 'a...f'
2814 ok
2815 Trying:
2816 "ajkml"
2817 Expecting:
2818 'a...l'
2819 ok
2820 1 items passed all tests:
2821 3 tests in myfile.doc
2822 3 tests in 1 items.
2823 3 passed and 0 failed.
2824 Test passed.
2825 Trying:
2826 1 + 1
2827 Expecting:
2828 2
2829 ok
2830 Trying:
2831 "abc def"
2832 Expecting:
2833 'abc def'
2834 ok
2835 1 items had no tests:
2836 myfile2
2837 1 items passed all tests:
2838 2 tests in myfile2.test_func
2839 2 tests in 2 items.
2840 2 passed and 0 failed.
2841 Test passed.
R David Murray5707d502013-06-23 14:24:13 -04002842
2843We should also check some typical error cases.
2844
2845Invalid file name:
2846
2847 >>> rc, out, err = script_helper.assert_python_failure(
R David Murray4af68982013-06-25 08:11:22 -04002848 ... '-m', 'doctest', 'nosuchfile', TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002849 >>> rc, out
2850 (1, b'')
R David Murray4af68982013-06-25 08:11:22 -04002851 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002852 Traceback (most recent call last):
2853 ...
2854 FileNotFoundError: [Errno ...] No such file or directory: 'nosuchfile'
2855
2856Invalid doctest option:
2857
2858 >>> rc, out, err = script_helper.assert_python_failure(
R David Murray4af68982013-06-25 08:11:22 -04002859 ... '-m', 'doctest', '-o', 'nosuchoption', TERM='')
R David Murray5707d502013-06-23 14:24:13 -04002860 >>> rc, out
2861 (2, b'')
R David Murray4af68982013-06-25 08:11:22 -04002862 >>> print(normalize(err)) # doctest: +ELLIPSIS
R David Murray5707d502013-06-23 14:24:13 -04002863 usage...invalid...nosuchoption...
2864
2865"""
2866
Tim Peters8485b562004-08-04 18:46:34 +00002867######################################################################
2868## Main
2869######################################################################
2870
2871def test_main():
2872 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002873 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002874 # Check the doctest cases defined here:
2875 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002876 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002877
Victor Stinner45df8202010-04-28 22:31:17 +00002878import sys, re, io
2879
Tim Peters8485b562004-08-04 18:46:34 +00002880def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002881 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01002882 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00002883 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002884 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002885 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002886 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002887 r.write_results(show_missing=True, summary=True,
2888 coverdir=coverdir)
2889
2890if __name__ == '__main__':
2891 if '-c' in sys.argv:
2892 test_coverage('/tmp/doctest.cover')
2893 else:
2894 test_main()