blob: 8f8c7c7e82b11ba642e0fe2208df0d1f0dd6ceeb [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
Tim Peters8485b562004-08-04 18:46:34 +0000412def test_DocTestFinder(): r"""
413Unit tests for the `DocTestFinder` class.
414
415DocTestFinder is used to extract DocTests from an object's docstring
416and the docstrings of its contained objects. It can be used with
417modules, functions, classes, methods, staticmethods, classmethods, and
418properties.
419
420Finding Tests in Functions
421~~~~~~~~~~~~~~~~~~~~~~~~~~
422For a function whose docstring contains examples, DocTestFinder.find()
423will return a single test (for that function's docstring):
424
Tim Peters8485b562004-08-04 18:46:34 +0000425 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000426
427We'll simulate a __file__ attr that ends in pyc:
428
429 >>> import test.test_doctest
430 >>> old = test.test_doctest.__file__
431 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
432
Tim Peters8485b562004-08-04 18:46:34 +0000433 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000434
Guido van Rossum7131f842007-02-09 20:13:25 +0000435 >>> print(tests) # doctest: +ELLIPSIS
Brett Cannon31f59292011-02-21 19:29:56 +0000436 [<DocTest sample_func from ...:18 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000437
Tim Peters4de7c5c2004-08-23 22:38:05 +0000438The exact name depends on how test_doctest was invoked, so allow for
439leading path components.
440
441 >>> tests[0].filename # doctest: +ELLIPSIS
442 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000443
444 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000445
Jim Fulton07a349c2004-08-22 14:10:00 +0000446
Tim Peters8485b562004-08-04 18:46:34 +0000447 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000448 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000449 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000450
Edward Loper32ddbf72004-09-13 05:47:24 +0000451By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000452
453 >>> def no_docstring(v):
454 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000455 >>> finder.find(no_docstring)
456 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000457
458However, the optional argument `exclude_empty` to the DocTestFinder
459constructor can be used to exclude tests for objects with empty
460docstrings:
461
462 >>> def no_docstring(v):
463 ... pass
464 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
465 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000466 []
467
468If the function has a docstring with no examples, then a test with no
469examples is returned. (This lets `DocTestRunner` collect statistics
470about which functions have no tests -- but is that useful? And should
471an empty test also be created when there's no docstring?)
472
473 >>> def no_examples(v):
474 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000475 >>> finder.find(no_examples) # doctest: +ELLIPSIS
476 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000477
478Finding Tests in Classes
479~~~~~~~~~~~~~~~~~~~~~~~~
480For a class, DocTestFinder will create a test for the class's
481docstring, and will recursively explore its contents, including
482methods, classmethods, staticmethods, properties, and nested classes.
483
484 >>> finder = doctest.DocTestFinder()
485 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000486 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000487 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000488 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000489 3 SampleClass.NestedClass
490 1 SampleClass.NestedClass.__init__
491 1 SampleClass.__init__
492 2 SampleClass.a_classmethod
493 1 SampleClass.a_property
494 1 SampleClass.a_staticmethod
495 1 SampleClass.double
496 1 SampleClass.get
497
498New-style classes are also supported:
499
500 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000501 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000502 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000503 1 SampleNewStyleClass
504 1 SampleNewStyleClass.__init__
505 1 SampleNewStyleClass.double
506 1 SampleNewStyleClass.get
507
508Finding Tests in Modules
509~~~~~~~~~~~~~~~~~~~~~~~~
510For a module, DocTestFinder will create a test for the class's
511docstring, and will recursively explore its contents, including
512functions, classes, and the `__test__` dictionary, if it exists:
513
514 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000515 >>> import types
516 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000517 >>> def triple(val):
518 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000519 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000520 ... 33
521 ... '''
522 ... return val*3
523 >>> m.__dict__.update({
524 ... 'sample_func': sample_func,
525 ... 'SampleClass': SampleClass,
526 ... '__doc__': '''
527 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000528 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000529 ... module
530 ... ''',
531 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000532 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000533 ... 'c': triple}})
534
535 >>> finder = doctest.DocTestFinder()
536 >>> # Use module=test.test_doctest, to prevent doctest from
537 >>> # ignoring the objects since they weren't defined in m.
538 >>> import test.test_doctest
539 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000540 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000541 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000542 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000543 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000544 3 some_module.SampleClass.NestedClass
545 1 some_module.SampleClass.NestedClass.__init__
546 1 some_module.SampleClass.__init__
547 2 some_module.SampleClass.a_classmethod
548 1 some_module.SampleClass.a_property
549 1 some_module.SampleClass.a_staticmethod
550 1 some_module.SampleClass.double
551 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000552 1 some_module.__test__.c
553 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000554 1 some_module.sample_func
555
556Duplicate Removal
557~~~~~~~~~~~~~~~~~
558If a single object is listed twice (under different names), then tests
559will only be generated for it once:
560
Tim Petersf3f57472004-08-08 06:11:48 +0000561 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000562 >>> assert doctest_aliases.TwoNames.f
563 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000564 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000565 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000566 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000567 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000568 test.doctest_aliases.TwoNames
569
570 TwoNames.f and TwoNames.g are bound to the same object.
571 We can't guess which will be found in doctest's traversal of
572 TwoNames.__dict__ first, so we have to allow for either.
573
574 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000575 True
576
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000577Empty Tests
578~~~~~~~~~~~
579By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000580
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000581 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000582 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000583 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000584 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000585 3 SampleClass.NestedClass
586 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000587 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000588 2 SampleClass.a_classmethod
589 1 SampleClass.a_property
590 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000591 1 SampleClass.double
592 1 SampleClass.get
593
594By default, that excluded objects with no doctests. exclude_empty=False
595tells it to include (empty) tests for objects with no doctests. This feature
596is really to support backward compatibility in what doctest.master.summarize()
597displays.
598
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000599 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000600 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000601 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000602 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000603 3 SampleClass.NestedClass
604 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000605 0 SampleClass.NestedClass.get
606 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000607 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000608 2 SampleClass.a_classmethod
609 1 SampleClass.a_property
610 1 SampleClass.a_staticmethod
611 1 SampleClass.double
612 1 SampleClass.get
613
Tim Peters8485b562004-08-04 18:46:34 +0000614Turning off Recursion
615~~~~~~~~~~~~~~~~~~~~~
616DocTestFinder can be told not to look for tests in contained objects
617using the `recurse` flag:
618
619 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000620 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000621 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000622 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000623
624Line numbers
625~~~~~~~~~~~~
626DocTestFinder finds the line number of each example:
627
628 >>> def f(x):
629 ... '''
630 ... >>> x = 12
631 ...
632 ... some text
633 ...
634 ... >>> # examples are not created for comments & bare prompts.
635 ... >>>
636 ... ...
637 ...
638 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000639 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000640 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000641 ... >>> x//2
642 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000643 ... '''
644 >>> test = doctest.DocTestFinder().find(f)[0]
645 >>> [e.lineno for e in test.examples]
646 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000647"""
648
Edward Loper00f8da72004-08-26 18:05:07 +0000649def test_DocTestParser(): r"""
650Unit tests for the `DocTestParser` class.
651
652DocTestParser is used to parse docstrings containing doctest examples.
653
654The `parse` method divides a docstring into examples and intervening
655text:
656
657 >>> s = '''
658 ... >>> x, y = 2, 3 # no output expected
659 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000660 ... ... print(x)
661 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000662 ... 2
663 ... 3
664 ...
665 ... Some text.
666 ... >>> x+y
667 ... 5
668 ... '''
669 >>> parser = doctest.DocTestParser()
670 >>> for piece in parser.parse(s):
671 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000672 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000673 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000674 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000675 Text: '\n'
676 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
677 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000678 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000679 Text: '\nSome text.\n'
680 Example: ('x+y\n', '5\n', 9)
681 Text: ''
682
683The `get_examples` method returns just the examples:
684
685 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000686 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000687 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000688 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000689 ('x+y\n', '5\n', 9)
690
691The `get_doctest` method creates a Test from the examples, along with the
692given arguments:
693
694 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
695 >>> (test.name, test.filename, test.lineno)
696 ('name', 'filename', 5)
697 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000698 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000699 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000700 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000701 ('x+y\n', '5\n', 9)
702"""
703
Tim Peters8485b562004-08-04 18:46:34 +0000704class test_DocTestRunner:
705 def basics(): r"""
706Unit tests for the `DocTestRunner` class.
707
708DocTestRunner is used to run DocTest test cases, and to accumulate
709statistics. Here's a simple DocTest case we can use:
710
711 >>> def f(x):
712 ... '''
713 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000714 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000715 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000716 ... >>> x//2
717 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000718 ... '''
719 >>> test = doctest.DocTestFinder().find(f)[0]
720
721The main DocTestRunner interface is the `run` method, which runs a
722given DocTest case in a given namespace (globs). It returns a tuple
723`(f,t)`, where `f` is the number of failed tests and `t` is the number
724of tried tests.
725
726 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000727 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000728
729If any example produces incorrect output, then the test runner reports
730the failure and proceeds to the next example:
731
732 >>> def f(x):
733 ... '''
734 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000735 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000736 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000737 ... >>> x//2
738 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000739 ... '''
740 >>> test = doctest.DocTestFinder().find(f)[0]
741 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000742 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000743 Trying:
744 x = 12
745 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000746 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000747 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000748 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000749 Expecting:
750 14
Tim Peters8485b562004-08-04 18:46:34 +0000751 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000752 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000753 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000754 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000755 Expected:
756 14
757 Got:
758 12
Edward Loperaacf0832004-08-26 01:19:50 +0000759 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000760 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000761 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000762 6
Tim Peters8485b562004-08-04 18:46:34 +0000763 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000764 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000765"""
766 def verbose_flag(): r"""
767The `verbose` flag makes the test runner generate more detailed
768output:
769
770 >>> def f(x):
771 ... '''
772 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000773 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000774 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000775 ... >>> x//2
776 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000777 ... '''
778 >>> test = doctest.DocTestFinder().find(f)[0]
779
780 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000781 Trying:
782 x = 12
783 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000784 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000785 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000786 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000787 Expecting:
788 12
Tim Peters8485b562004-08-04 18:46:34 +0000789 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000790 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000791 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000792 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000793 6
Tim Peters8485b562004-08-04 18:46:34 +0000794 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000795 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000796
797If the `verbose` flag is unspecified, then the output will be verbose
798iff `-v` appears in sys.argv:
799
800 >>> # Save the real sys.argv list.
801 >>> old_argv = sys.argv
802
803 >>> # If -v does not appear in sys.argv, then output isn't verbose.
804 >>> sys.argv = ['test']
805 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000806 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000807
808 >>> # If -v does appear in sys.argv, then output is verbose.
809 >>> sys.argv = ['test', '-v']
810 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000811 Trying:
812 x = 12
813 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000814 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000815 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000816 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000817 Expecting:
818 12
Tim Peters8485b562004-08-04 18:46:34 +0000819 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000820 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000821 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000822 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000823 6
Tim Peters8485b562004-08-04 18:46:34 +0000824 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000825 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000826
827 >>> # Restore sys.argv
828 >>> sys.argv = old_argv
829
830In the remaining examples, the test runner's verbosity will be
831explicitly set, to ensure that the test behavior is consistent.
832 """
833 def exceptions(): r"""
834Tests of `DocTestRunner`'s exception handling.
835
836An expected exception is specified with a traceback message. The
837lines between the first line and the type/value may be omitted or
838replaced with any other string:
839
840 >>> def f(x):
841 ... '''
842 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000843 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000844 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000846 ... '''
847 >>> test = doctest.DocTestFinder().find(f)[0]
848 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000849 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000850
Edward Loper19b19582004-08-25 23:07:03 +0000851An example may not generate output before it raises an exception; if
852it does, then the traceback message will not be recognized as
853signaling an expected exception, so the example will be reported as an
854unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000855
856 >>> def f(x):
857 ... '''
858 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000859 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000860 ... pre-exception output
861 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000862 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000863 ... '''
864 >>> test = doctest.DocTestFinder().find(f)[0]
865 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000866 ... # doctest: +ELLIPSIS
867 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000868 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000869 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000870 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000871 Exception raised:
872 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000873 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000874 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000875
876Exception messages may contain newlines:
877
878 >>> def f(x):
879 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000880 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000881 ... Traceback (most recent call last):
882 ... ValueError: multi
883 ... line
884 ... message
885 ... '''
886 >>> test = doctest.DocTestFinder().find(f)[0]
887 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000888 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000889
890If an exception is expected, but an exception with the wrong type or
891message is raised, then it is reported as a failure:
892
893 >>> def f(x):
894 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000895 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000896 ... Traceback (most recent call last):
897 ... ValueError: wrong message
898 ... '''
899 >>> test = doctest.DocTestFinder().find(f)[0]
900 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000901 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000902 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000903 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000904 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000905 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000906 Expected:
907 Traceback (most recent call last):
908 ValueError: wrong message
909 Got:
910 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000911 ...
Tim Peters8485b562004-08-04 18:46:34 +0000912 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000913 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000914
Tim Peters1fbf9c52004-09-04 17:21:02 +0000915However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
916detail:
917
918 >>> def f(x):
919 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000920 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000921 ... Traceback (most recent call last):
922 ... ValueError: wrong message
923 ... '''
924 >>> test = doctest.DocTestFinder().find(f)[0]
925 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000926 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000927
Nick Coghlan5e76e942010-06-12 13:42:46 +0000928IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
929between Python versions. For example, in Python 2.x, the module path of
930the exception is not in the output, but this will fail under Python 3:
931
932 >>> def f(x):
933 ... r'''
934 ... >>> from http.client import HTTPException
935 ... >>> raise HTTPException('message')
936 ... Traceback (most recent call last):
937 ... HTTPException: message
938 ... '''
939 >>> test = doctest.DocTestFinder().find(f)[0]
940 >>> doctest.DocTestRunner(verbose=False).run(test)
941 ... # doctest: +ELLIPSIS
942 **********************************************************************
943 File ..., line 4, in f
944 Failed example:
945 raise HTTPException('message')
946 Expected:
947 Traceback (most recent call last):
948 HTTPException: message
949 Got:
950 Traceback (most recent call last):
951 ...
952 http.client.HTTPException: message
953 TestResults(failed=1, attempted=2)
954
955But in Python 3 the module path is included, and therefore a test must look
956like the following test to succeed in Python 3. But that test will fail under
957Python 2.
958
959 >>> def f(x):
960 ... r'''
961 ... >>> from http.client import HTTPException
962 ... >>> raise HTTPException('message')
963 ... Traceback (most recent call last):
964 ... http.client.HTTPException: message
965 ... '''
966 >>> test = doctest.DocTestFinder().find(f)[0]
967 >>> doctest.DocTestRunner(verbose=False).run(test)
968 TestResults(failed=0, attempted=2)
969
970However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
971(or its unexpected absence) will be ignored:
972
973 >>> def f(x):
974 ... r'''
975 ... >>> from http.client import HTTPException
976 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
977 ... Traceback (most recent call last):
978 ... HTTPException: message
979 ... '''
980 >>> test = doctest.DocTestFinder().find(f)[0]
981 >>> doctest.DocTestRunner(verbose=False).run(test)
982 TestResults(failed=0, attempted=2)
983
984The module path will be completely ignored, so two different module paths will
985still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
986be used when exceptions have changed module.
987
988 >>> def f(x):
989 ... r'''
990 ... >>> from http.client import HTTPException
991 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
992 ... Traceback (most recent call last):
993 ... foo.bar.HTTPException: message
994 ... '''
995 >>> test = doctest.DocTestFinder().find(f)[0]
996 >>> doctest.DocTestRunner(verbose=False).run(test)
997 TestResults(failed=0, attempted=2)
998
Tim Peters1fbf9c52004-09-04 17:21:02 +0000999But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1000
1001 >>> def f(x):
1002 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001003 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001004 ... Traceback (most recent call last):
1005 ... TypeError: wrong type
1006 ... '''
1007 >>> test = doctest.DocTestFinder().find(f)[0]
1008 >>> doctest.DocTestRunner(verbose=False).run(test)
1009 ... # doctest: +ELLIPSIS
1010 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001011 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001012 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001013 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001014 Expected:
1015 Traceback (most recent call last):
1016 TypeError: wrong type
1017 Got:
1018 Traceback (most recent call last):
1019 ...
1020 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001021 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001022
Tim Peters8485b562004-08-04 18:46:34 +00001023If an exception is raised but not expected, then it is reported as an
1024unexpected exception:
1025
Tim Peters8485b562004-08-04 18:46:34 +00001026 >>> def f(x):
1027 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001028 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001029 ... 0
1030 ... '''
1031 >>> test = doctest.DocTestFinder().find(f)[0]
1032 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001033 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001034 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001035 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001036 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001037 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001038 Exception raised:
1039 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001040 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001041 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001042 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001043"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001044 def displayhook(): r"""
1045Test that changing sys.displayhook doesn't matter for doctest.
1046
1047 >>> import sys
1048 >>> orig_displayhook = sys.displayhook
1049 >>> def my_displayhook(x):
1050 ... print('hi!')
1051 >>> sys.displayhook = my_displayhook
1052 >>> def f():
1053 ... '''
1054 ... >>> 3
1055 ... 3
1056 ... '''
1057 >>> test = doctest.DocTestFinder().find(f)[0]
1058 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1059 >>> post_displayhook = sys.displayhook
1060
1061 We need to restore sys.displayhook now, so that we'll be able to test
1062 results.
1063
1064 >>> sys.displayhook = orig_displayhook
1065
1066 Ok, now we can check that everything is ok.
1067
1068 >>> r
1069 TestResults(failed=0, attempted=1)
1070 >>> post_displayhook is my_displayhook
1071 True
1072"""
Tim Peters8485b562004-08-04 18:46:34 +00001073 def optionflags(): r"""
1074Tests of `DocTestRunner`'s option flag handling.
1075
1076Several option flags can be used to customize the behavior of the test
1077runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001078to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001079together).
1080
1081The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1082and 1/0:
1083
1084 >>> def f(x):
1085 ... '>>> True\n1\n'
1086
1087 >>> # Without the flag:
1088 >>> test = doctest.DocTestFinder().find(f)[0]
1089 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001090 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001091
1092 >>> # With the flag:
1093 >>> test = doctest.DocTestFinder().find(f)[0]
1094 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1095 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001096 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001097 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001098 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001099 Failed example:
1100 True
1101 Expected:
1102 1
1103 Got:
1104 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001105 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001106
1107The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1108and the '<BLANKLINE>' marker:
1109
1110 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001111 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001112
1113 >>> # Without the flag:
1114 >>> test = doctest.DocTestFinder().find(f)[0]
1115 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001116 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001117
1118 >>> # With the flag:
1119 >>> test = doctest.DocTestFinder().find(f)[0]
1120 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1121 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001122 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001123 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001124 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001125 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001126 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001127 Expected:
1128 a
1129 <BLANKLINE>
1130 b
1131 Got:
1132 a
1133 <BLANKLINE>
1134 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001135 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001136
1137The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1138treated as equal:
1139
1140 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001141 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001142
1143 >>> # Without the flag:
1144 >>> test = doctest.DocTestFinder().find(f)[0]
1145 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001146 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001147 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001148 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001149 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001150 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001151 Expected:
1152 1 2
1153 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001154 Got:
1155 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001156 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001157
1158 >>> # With the flag:
1159 >>> test = doctest.DocTestFinder().find(f)[0]
1160 >>> flags = doctest.NORMALIZE_WHITESPACE
1161 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001162 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001163
Tim Peters026f8dc2004-08-19 16:38:58 +00001164 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001165 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001166 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1167 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1168
Tim Peters8485b562004-08-04 18:46:34 +00001169The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1170output to match any substring in the actual output:
1171
1172 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001173 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001174
1175 >>> # Without the flag:
1176 >>> test = doctest.DocTestFinder().find(f)[0]
1177 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001178 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001179 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001180 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001181 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001182 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001183 Expected:
1184 [0, 1, 2, ..., 14]
1185 Got:
1186 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001187 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001188
1189 >>> # With the flag:
1190 >>> test = doctest.DocTestFinder().find(f)[0]
1191 >>> flags = doctest.ELLIPSIS
1192 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001193 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001194
Tim Peterse594bee2004-08-22 01:47:51 +00001195 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001196
Guido van Rossume0192e52007-02-09 23:39:59 +00001197 >>> if 1:
1198 ... for i in range(100):
1199 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1200 ... print('!')
1201 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001202
Tim Peters026f8dc2004-08-19 16:38:58 +00001203 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001204
Guido van Rossume0192e52007-02-09 23:39:59 +00001205 >>> if 1: #doctest: +ELLIPSIS
1206 ... for i in range(20):
1207 ... print(i, end=' ')
1208 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001209 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001210
Tim Peters026f8dc2004-08-19 16:38:58 +00001211 Examples from the docs:
1212
Guido van Rossum805365e2007-05-07 22:24:25 +00001213 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001214 [0, 1, ..., 18, 19]
1215
Guido van Rossum805365e2007-05-07 22:24:25 +00001216 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001217 ... # doctest: +NORMALIZE_WHITESPACE
1218 [0, 1, ..., 18, 19]
1219
Thomas Wouters477c8d52006-05-27 19:21:47 +00001220The SKIP flag causes an example to be skipped entirely. I.e., the
1221example is not run. It can be useful in contexts where doctest
1222examples serve as both documentation and test cases, and an example
1223should be included for documentation purposes, but should not be
1224checked (e.g., because its output is random, or depends on resources
1225which would be unavailable.) The SKIP flag can also be used for
1226'commenting out' broken examples.
1227
1228 >>> import unavailable_resource # doctest: +SKIP
1229 >>> unavailable_resource.do_something() # doctest: +SKIP
1230 >>> unavailable_resource.blow_up() # doctest: +SKIP
1231 Traceback (most recent call last):
1232 ...
1233 UncheckedBlowUpError: Nobody checks me.
1234
1235 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001236 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001237 0.721216923889
1238
Edward Loper71f55af2004-08-26 01:41:51 +00001239The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001240and actual outputs to be displayed using a unified diff:
1241
1242 >>> def f(x):
1243 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001244 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001245 ... a
1246 ... B
1247 ... c
1248 ... d
1249 ... f
1250 ... g
1251 ... h
1252 ... '''
1253
1254 >>> # Without the flag:
1255 >>> test = doctest.DocTestFinder().find(f)[0]
1256 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001257 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001258 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001259 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001260 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001261 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001262 Expected:
1263 a
1264 B
1265 c
1266 d
1267 f
1268 g
1269 h
1270 Got:
1271 a
1272 b
1273 c
1274 d
1275 e
1276 f
1277 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001278 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001279
1280 >>> # With the flag:
1281 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001282 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001283 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001284 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001285 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001286 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001287 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001288 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001289 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001290 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001291 a
1292 -B
1293 +b
1294 c
1295 d
1296 +e
1297 f
1298 g
1299 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001300 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001301
Edward Loper71f55af2004-08-26 01:41:51 +00001302The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001303and actual outputs to be displayed using a context diff:
1304
Edward Loper71f55af2004-08-26 01:41:51 +00001305 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001306 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001307 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001308 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001309 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001310 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001311 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001312 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001313 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001314 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001315 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001316 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001317 a
1318 ! B
1319 c
1320 d
1321 f
1322 g
1323 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001324 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001325 a
1326 ! b
1327 c
1328 d
1329 + e
1330 f
1331 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001332 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001333
1334
Edward Loper71f55af2004-08-26 01:41:51 +00001335The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001336used by the popular ndiff.py utility. This does intraline difference
1337marking, as well as interline differences.
1338
1339 >>> def f(x):
1340 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001341 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001342 ... a b c d e f g h i j k 1 m
1343 ... '''
1344 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001345 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001346 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001347 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001348 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001349 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001350 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001351 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001352 Differences (ndiff with -expected +actual):
1353 - a b c d e f g h i j k 1 m
1354 ? ^
1355 + a b c d e f g h i j k l m
1356 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001357 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001358
Ezio Melotti13925002011-03-16 11:05:33 +02001359The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001360failing example:
1361
1362 >>> def f(x):
1363 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001364 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001365 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001366 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001367 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001368 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001369 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001370 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001371 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001372 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001373 ... 500
1374 ... '''
1375 >>> test = doctest.DocTestFinder().find(f)[0]
1376 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1377 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001378 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001379 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001380 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001381 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001382 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001383 Expected:
1384 200
1385 Got:
1386 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001387 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001388
Ezio Melotti13925002011-03-16 11:05:33 +02001389However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001390
1391 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001392 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001393 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001394 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001395 Expecting:
1396 1
1397 ok
1398 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001399 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001400 Expecting:
1401 200
1402 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001403 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001404 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001405 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001406 Expected:
1407 200
1408 Got:
1409 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001410 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001411
1412For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1413count as failures:
1414
1415 >>> def f(x):
1416 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001417 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001418 ... 1
1419 ... >>> raise ValueError(2) # first failure
1420 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001421 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001422 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001423 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001424 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001425 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001426 ... 500
1427 ... '''
1428 >>> test = doctest.DocTestFinder().find(f)[0]
1429 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1430 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1431 ... # doctest: +ELLIPSIS
1432 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001433 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001434 Failed example:
1435 raise ValueError(2) # first failure
1436 Exception raised:
1437 ...
1438 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001439 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001440
Thomas Wouters477c8d52006-05-27 19:21:47 +00001441New option flags can also be registered, via register_optionflag(). Here
1442we reach into doctest's internals a bit.
1443
1444 >>> unlikely = "UNLIKELY_OPTION_NAME"
1445 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1446 False
1447 >>> new_flag_value = doctest.register_optionflag(unlikely)
1448 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1449 True
1450
1451Before 2.4.4/2.5, registering a name more than once erroneously created
1452more than one flag value. Here we verify that's fixed:
1453
1454 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1455 >>> redundant_flag_value == new_flag_value
1456 True
1457
1458Clean up.
1459 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1460
Tim Petersc6cbab02004-08-22 19:43:28 +00001461 """
1462
Tim Peters8485b562004-08-04 18:46:34 +00001463 def option_directives(): r"""
1464Tests of `DocTestRunner`'s option directive mechanism.
1465
Edward Loper74bca7a2004-08-12 02:27:44 +00001466Option directives can be used to turn option flags on or off for a
1467single example. To turn an option on for an example, follow that
1468example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001469
1470 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001471 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001472 ... [0, 1, ..., 9]
1473 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001474 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001475 ... [0, 1, ..., 9]
1476 ... '''
1477 >>> test = doctest.DocTestFinder().find(f)[0]
1478 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001479 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001480 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001481 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001482 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001483 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001484 Expected:
1485 [0, 1, ..., 9]
1486 Got:
1487 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001488 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001489
1490To turn an option off for an example, follow that example with a
1491comment of the form ``# doctest: -OPTION``:
1492
1493 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001494 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001495 ... [0, 1, ..., 9]
1496 ...
1497 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001498 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001499 ... [0, 1, ..., 9]
1500 ... '''
1501 >>> test = doctest.DocTestFinder().find(f)[0]
1502 >>> doctest.DocTestRunner(verbose=False,
1503 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001504 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001505 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001506 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001507 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001508 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001509 Expected:
1510 [0, 1, ..., 9]
1511 Got:
1512 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001513 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001514
1515Option directives affect only the example that they appear with; they
1516do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001517
Edward Loper74bca7a2004-08-12 02:27:44 +00001518 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001519 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001520 ... [0, 1, ..., 9]
1521 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001522 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001523 ... [0, 1, ..., 9]
1524 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001525 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001526 ... [0, 1, ..., 9]
1527 ... '''
1528 >>> test = doctest.DocTestFinder().find(f)[0]
1529 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001530 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001531 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001532 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001533 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001534 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001535 Expected:
1536 [0, 1, ..., 9]
1537 Got:
1538 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001539 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001540 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001541 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001542 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001543 Expected:
1544 [0, 1, ..., 9]
1545 Got:
1546 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001547 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001548
Edward Loper74bca7a2004-08-12 02:27:44 +00001549Multiple options may be modified by a single option directive. They
1550may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001551
1552 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001553 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001554 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001555 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001556 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001557 ... [0, 1, ..., 9]
1558 ... '''
1559 >>> test = doctest.DocTestFinder().find(f)[0]
1560 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001561 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001562 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001563 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001564 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001565 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001566 Expected:
1567 [0, 1, ..., 9]
1568 Got:
1569 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001570 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001571
1572 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001573 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001574 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001575 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001576 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1577 ... [0, 1, ..., 9]
1578 ... '''
1579 >>> test = doctest.DocTestFinder().find(f)[0]
1580 >>> doctest.DocTestRunner(verbose=False).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 2, 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))) # Should fail
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
1592 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001593 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001594 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001595 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001596 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1597 ... [0, 1, ..., 9]
1598 ... '''
1599 >>> test = doctest.DocTestFinder().find(f)[0]
1600 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001601 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001602 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001603 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001604 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001605 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001606 Expected:
1607 [0, 1, ..., 9]
1608 Got:
1609 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001610 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001611
1612The option directive may be put on the line following the source, as
1613long as a continuation prompt is used:
1614
1615 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001616 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001617 ... ... # doctest: +ELLIPSIS
1618 ... [0, 1, ..., 9]
1619 ... '''
1620 >>> test = doctest.DocTestFinder().find(f)[0]
1621 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001622 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001623
Edward Loper74bca7a2004-08-12 02:27:44 +00001624For examples with multi-line source, the option directive may appear
1625at the end of any line:
1626
1627 >>> def f(x): r'''
1628 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001629 ... ... print(' ', x, end='', sep='')
1630 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001631 ...
1632 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001633 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1634 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001635 ... '''
1636 >>> test = doctest.DocTestFinder().find(f)[0]
1637 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001638 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001639
1640If more than one line of an example with multi-line source has an
1641option directive, then they are combined:
1642
1643 >>> def f(x): r'''
1644 ... Should fail (option directive not on the last line):
1645 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001646 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001647 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001648 ... '''
1649 >>> test = doctest.DocTestFinder().find(f)[0]
1650 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001651 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001652
1653It is an error to have a comment of the form ``# doctest:`` that is
1654*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1655``OPTION`` is an option that has been registered with
1656`register_option`:
1657
1658 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001659 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001660 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1661 Traceback (most recent call last):
1662 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1663
1664 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001665 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001666 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1667 Traceback (most recent call last):
1668 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1669
1670It is an error to use an option directive on a line that contains no
1671source:
1672
1673 >>> s = '>>> # doctest: +ELLIPSIS'
1674 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1675 Traceback (most recent call last):
1676 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 +00001677"""
1678
1679def test_testsource(): r"""
1680Unit tests for `testsource()`.
1681
1682The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001683test with that name in that module, and converts it to a script. The
1684example code is converted to regular Python code. The surrounding
1685words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001686
1687 >>> import test.test_doctest
1688 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001689 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001690 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001691 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001692 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001693 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001694 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001695 #
Edward Lopera5db6002004-08-12 02:41:30 +00001696 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001697 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001698
1699 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001700 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001701 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001702 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001703 ## 1
1704 ## 2
1705 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001706 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001707
1708 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001709 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001710 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001711 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001712 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001713 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001714 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001715 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001716 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001717"""
1718
1719def test_debug(): r"""
1720
1721Create a docstring that we want to debug:
1722
1723 >>> s = '''
1724 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001725 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001726 ... 12
1727 ... '''
1728
1729Create some fake stdin input, to feed to the debugger:
1730
Tim Peters8485b562004-08-04 18:46:34 +00001731 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001732 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001733
1734Run the debugger on the docstring, and then restore sys.stdin.
1735
Edward Loper2de91ba2004-08-27 02:07:46 +00001736 >>> try: doctest.debug_src(s)
1737 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001738 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001739 (Pdb) next
1740 12
Tim Peters8485b562004-08-04 18:46:34 +00001741 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001742 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001743 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001744 12
1745 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001746
1747"""
1748
Brett Cannon31f59292011-02-21 19:29:56 +00001749if not hasattr(sys, 'gettrace') or not sys.gettrace():
1750 def test_pdb_set_trace():
1751 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001752
Brett Cannon31f59292011-02-21 19:29:56 +00001753 You can use pdb.set_trace from a doctest. To do so, you must
1754 retrieve the set_trace function from the pdb module at the time
1755 you use it. The doctest module changes sys.stdout so that it can
1756 capture program output. It also temporarily replaces pdb.set_trace
1757 with a version that restores stdout. This is necessary for you to
1758 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001759
Brett Cannon31f59292011-02-21 19:29:56 +00001760 >>> doc = '''
1761 ... >>> x = 42
1762 ... >>> raise Exception('clé')
1763 ... Traceback (most recent call last):
1764 ... Exception: clé
1765 ... >>> import pdb; pdb.set_trace()
1766 ... '''
1767 >>> parser = doctest.DocTestParser()
1768 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1769 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001770
Brett Cannon31f59292011-02-21 19:29:56 +00001771 To demonstrate this, we'll create a fake standard input that
1772 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001773
Brett Cannon31f59292011-02-21 19:29:56 +00001774 >>> import tempfile
1775 >>> real_stdin = sys.stdin
1776 >>> sys.stdin = _FakeInput([
1777 ... 'print(x)', # print data defined by the example
1778 ... 'continue', # stop debugging
1779 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001780
Brett Cannon31f59292011-02-21 19:29:56 +00001781 >>> try: runner.run(test)
1782 ... finally: sys.stdin = real_stdin
1783 --Return--
1784 > <doctest foo-bar@baz[2]>(1)<module>()->None
1785 -> import pdb; pdb.set_trace()
1786 (Pdb) print(x)
1787 42
1788 (Pdb) continue
1789 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001790
Brett Cannon31f59292011-02-21 19:29:56 +00001791 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001792
Brett Cannon31f59292011-02-21 19:29:56 +00001793 >>> def calls_set_trace():
1794 ... y=2
1795 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001796
Brett Cannon31f59292011-02-21 19:29:56 +00001797 >>> doc = '''
1798 ... >>> x=1
1799 ... >>> calls_set_trace()
1800 ... '''
1801 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1802 >>> real_stdin = sys.stdin
1803 >>> sys.stdin = _FakeInput([
1804 ... 'print(y)', # print data defined in the function
1805 ... 'up', # out of function
1806 ... 'print(x)', # print data defined by the example
1807 ... 'continue', # stop debugging
1808 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001809
Brett Cannon31f59292011-02-21 19:29:56 +00001810 >>> try:
1811 ... runner.run(test)
1812 ... finally:
1813 ... sys.stdin = real_stdin
1814 --Return--
1815 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1816 -> import pdb; pdb.set_trace()
1817 (Pdb) print(y)
1818 2
1819 (Pdb) up
1820 > <doctest foo-bar@baz[1]>(1)<module>()
1821 -> calls_set_trace()
1822 (Pdb) print(x)
1823 1
1824 (Pdb) continue
1825 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001826
Brett Cannon31f59292011-02-21 19:29:56 +00001827 During interactive debugging, source code is shown, even for
1828 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001829
Brett Cannon31f59292011-02-21 19:29:56 +00001830 >>> doc = '''
1831 ... >>> def f(x):
1832 ... ... g(x*2)
1833 ... >>> def g(x):
1834 ... ... print(x+3)
1835 ... ... import pdb; pdb.set_trace()
1836 ... >>> f(3)
1837 ... '''
1838 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1839 >>> real_stdin = sys.stdin
1840 >>> sys.stdin = _FakeInput([
1841 ... 'list', # list source from example 2
1842 ... 'next', # return from g()
1843 ... 'list', # list source from example 1
1844 ... 'next', # return from f()
1845 ... 'list', # list source from example 3
1846 ... 'continue', # stop debugging
1847 ... ''])
1848 >>> try: runner.run(test)
1849 ... finally: sys.stdin = real_stdin
1850 ... # doctest: +NORMALIZE_WHITESPACE
1851 --Return--
1852 > <doctest foo-bar@baz[1]>(3)g()->None
1853 -> import pdb; pdb.set_trace()
1854 (Pdb) list
1855 1 def g(x):
1856 2 print(x+3)
1857 3 -> import pdb; pdb.set_trace()
1858 [EOF]
1859 (Pdb) next
1860 --Return--
1861 > <doctest foo-bar@baz[0]>(2)f()->None
1862 -> g(x*2)
1863 (Pdb) list
1864 1 def f(x):
1865 2 -> g(x*2)
1866 [EOF]
1867 (Pdb) next
1868 --Return--
1869 > <doctest foo-bar@baz[2]>(1)<module>()->None
1870 -> f(3)
1871 (Pdb) list
1872 1 -> f(3)
1873 [EOF]
1874 (Pdb) continue
1875 **********************************************************************
1876 File "foo-bar@baz.py", line 7, in foo-bar@baz
1877 Failed example:
1878 f(3)
1879 Expected nothing
1880 Got:
1881 9
1882 TestResults(failed=1, attempted=3)
1883 """
Jim Fulton356fd192004-08-09 11:34:47 +00001884
Brett Cannon31f59292011-02-21 19:29:56 +00001885 def test_pdb_set_trace_nested():
1886 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00001887
Brett Cannon31f59292011-02-21 19:29:56 +00001888 >>> class C(object):
1889 ... def calls_set_trace(self):
1890 ... y = 1
1891 ... import pdb; pdb.set_trace()
1892 ... self.f1()
1893 ... y = 2
1894 ... def f1(self):
1895 ... x = 1
1896 ... self.f2()
1897 ... x = 2
1898 ... def f2(self):
1899 ... z = 1
1900 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00001901
Brett Cannon31f59292011-02-21 19:29:56 +00001902 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00001903
Brett Cannon31f59292011-02-21 19:29:56 +00001904 >>> doc = '''
1905 ... >>> a = 1
1906 ... >>> calls_set_trace()
1907 ... '''
1908 >>> parser = doctest.DocTestParser()
1909 >>> runner = doctest.DocTestRunner(verbose=False)
1910 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1911 >>> real_stdin = sys.stdin
1912 >>> sys.stdin = _FakeInput([
1913 ... 'print(y)', # print data defined in the function
1914 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1915 ... 'up', 'print(x)',
1916 ... 'up', 'print(y)',
1917 ... 'up', 'print(foo)',
1918 ... 'continue', # stop debugging
1919 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00001920
Brett Cannon31f59292011-02-21 19:29:56 +00001921 >>> try:
1922 ... runner.run(test)
1923 ... finally:
1924 ... sys.stdin = real_stdin
1925 ... # doctest: +REPORT_NDIFF
1926 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1927 -> self.f1()
1928 (Pdb) print(y)
1929 1
1930 (Pdb) step
1931 --Call--
1932 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1933 -> def f1(self):
1934 (Pdb) step
1935 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1936 -> x = 1
1937 (Pdb) step
1938 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1939 -> self.f2()
1940 (Pdb) step
1941 --Call--
1942 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1943 -> def f2(self):
1944 (Pdb) step
1945 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1946 -> z = 1
1947 (Pdb) step
1948 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1949 -> z = 2
1950 (Pdb) print(z)
1951 1
1952 (Pdb) up
1953 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1954 -> self.f2()
1955 (Pdb) print(x)
1956 1
1957 (Pdb) up
1958 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1959 -> self.f1()
1960 (Pdb) print(y)
1961 1
1962 (Pdb) up
1963 > <doctest foo-bar@baz[1]>(1)<module>()
1964 -> calls_set_trace()
1965 (Pdb) print(foo)
1966 *** NameError: name 'foo' is not defined
1967 (Pdb) continue
1968 TestResults(failed=0, attempted=2)
1969 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00001970
Tim Peters19397e52004-08-06 22:02:59 +00001971def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001972 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001973
1974 We create a Suite by providing a module. A module can be provided
1975 by passing a module object:
1976
1977 >>> import unittest
1978 >>> import test.sample_doctest
1979 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1980 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001981 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001982
1983 We can also supply the module by name:
1984
1985 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1986 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001987 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001988
R David Murray5abd76a2012-09-10 10:15:58 -04001989 The module need not contain any doctest examples:
1990
1991 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
1992 >>> suite.run(unittest.TestResult())
1993 <unittest.result.TestResult run=0 errors=0 failures=0>
1994
1995 However, if DocTestSuite finds no docstrings, it raises an error:
1996
1997 >>> try:
1998 ... doctest.DocTestSuite('test.sample_doctest_no_docstrings')
1999 ... except ValueError as e:
2000 ... error = e
2001
2002 >>> print(error.args[1])
2003 has no docstrings
2004
2005 You can prevent this error by passing a DocTestFinder instance with
2006 the `exclude_empty` keyword argument set to False:
2007
2008 >>> finder = doctest.DocTestFinder(exclude_empty=False)
2009 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2010 ... test_finder=finder)
2011 >>> suite.run(unittest.TestResult())
2012 <unittest.result.TestResult run=0 errors=0 failures=0>
2013
Tim Peters19397e52004-08-06 22:02:59 +00002014 We can use the current module:
2015
2016 >>> suite = test.sample_doctest.test_suite()
2017 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002018 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002019
2020 We can supply global variables. If we pass globs, they will be
2021 used instead of the module globals. Here we'll pass an empty
2022 globals, triggering an extra error:
2023
2024 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2025 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002026 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002027
2028 Alternatively, we can provide extra globals. Here we'll make an
2029 error go away by providing an extra global variable:
2030
2031 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2032 ... extraglobs={'y': 1})
2033 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002034 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002035
2036 You can pass option flags. Here we'll cause an extra error
2037 by disabling the blank-line feature:
2038
2039 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002040 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002041 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002042 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002043
Tim Peters1e277ee2004-08-07 05:37:52 +00002044 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002045
Jim Fultonf54bad42004-08-28 14:57:56 +00002046 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002047 ... import test.test_doctest
2048 ... test.test_doctest.sillySetup = True
2049
Jim Fultonf54bad42004-08-28 14:57:56 +00002050 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002051 ... import test.test_doctest
2052 ... del test.test_doctest.sillySetup
2053
2054 Here, we installed a silly variable that the test expects:
2055
2056 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2057 ... setUp=setUp, tearDown=tearDown)
2058 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002059 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002060
2061 But the tearDown restores sanity:
2062
2063 >>> import test.test_doctest
2064 >>> test.test_doctest.sillySetup
2065 Traceback (most recent call last):
2066 ...
2067 AttributeError: 'module' object has no attribute 'sillySetup'
2068
Jim Fultonf54bad42004-08-28 14:57:56 +00002069 The setUp and tearDown funtions are passed test objects. Here
2070 we'll use the setUp function to supply the missing variable y:
2071
2072 >>> def setUp(test):
2073 ... test.globs['y'] = 1
2074
2075 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2076 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002077 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002078
2079 Here, we didn't need to use a tearDown function because we
2080 modified the test globals, which are a copy of the
2081 sample_doctest module dictionary. The test globals are
2082 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002083 """
2084
2085def test_DocFileSuite():
2086 """We can test tests found in text files using a DocFileSuite.
2087
2088 We create a suite by providing the names of one or more text
2089 files that include examples:
2090
2091 >>> import unittest
2092 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002093 ... 'test_doctest2.txt',
2094 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002095 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002096 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002097
2098 The test files are looked for in the directory containing the
2099 calling module. A package keyword argument can be provided to
2100 specify a different relative location.
2101
2102 >>> import unittest
2103 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2104 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002105 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002106 ... package='test')
2107 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002108 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002109
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002110 Support for using a package's __loader__.get_data() is also
2111 provided.
2112
2113 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002114 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002115 >>> if not hasattr(test, '__loader__'):
2116 ... test.__loader__ = pkgutil.get_loader(test)
2117 ... added_loader = True
2118 >>> try:
2119 ... suite = doctest.DocFileSuite('test_doctest.txt',
2120 ... 'test_doctest2.txt',
2121 ... 'test_doctest4.txt',
2122 ... package='test')
2123 ... suite.run(unittest.TestResult())
2124 ... finally:
2125 ... if added_loader:
2126 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002127 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002128
Edward Loper0273f5b2004-09-18 20:27:04 +00002129 '/' should be used as a path separator. It will be converted
2130 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002131
2132 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2133 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002134 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002135
Edward Loper0273f5b2004-09-18 20:27:04 +00002136 If DocFileSuite is used from an interactive session, then files
2137 are resolved relative to the directory of sys.argv[0]:
2138
Christian Heimes45f9af32007-11-27 21:50:00 +00002139 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002140 >>> save_argv = sys.argv
2141 >>> sys.argv = [test.test_doctest.__file__]
2142 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002143 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002144 >>> sys.argv = save_argv
2145
Edward Loper052d0cd2004-09-19 17:19:33 +00002146 By setting `module_relative=False`, os-specific paths may be
2147 used (including absolute paths and paths relative to the
2148 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002149
2150 >>> # Get the absolute path of the test package.
2151 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2152 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2153
2154 >>> # Use it to find the absolute path of test_doctest.txt.
2155 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2156
Edward Loper052d0cd2004-09-19 17:19:33 +00002157 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002158 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002159 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002160
Edward Loper052d0cd2004-09-19 17:19:33 +00002161 It is an error to specify `package` when `module_relative=False`:
2162
2163 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2164 ... package='test')
2165 Traceback (most recent call last):
2166 ValueError: Package may only be specified for module-relative paths.
2167
Tim Peters19397e52004-08-06 22:02:59 +00002168 You can specify initial global variables:
2169
2170 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2171 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002172 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002173 ... globs={'favorite_color': 'blue'})
2174 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002175 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002176
2177 In this case, we supplied a missing favorite color. You can
2178 provide doctest options:
2179
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 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2184 ... globs={'favorite_color': 'blue'})
2185 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002186 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002187
2188 And, you can provide setUp and tearDown functions:
2189
Jim Fultonf54bad42004-08-28 14:57:56 +00002190 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002191 ... import test.test_doctest
2192 ... test.test_doctest.sillySetup = True
2193
Jim Fultonf54bad42004-08-28 14:57:56 +00002194 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002195 ... import test.test_doctest
2196 ... del test.test_doctest.sillySetup
2197
2198 Here, we installed a silly variable that the test expects:
2199
2200 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2201 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002202 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002203 ... setUp=setUp, tearDown=tearDown)
2204 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002205 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002206
2207 But the tearDown restores sanity:
2208
2209 >>> import test.test_doctest
2210 >>> test.test_doctest.sillySetup
2211 Traceback (most recent call last):
2212 ...
2213 AttributeError: 'module' object has no attribute 'sillySetup'
2214
Jim Fultonf54bad42004-08-28 14:57:56 +00002215 The setUp and tearDown funtions are passed test objects.
2216 Here, we'll use a setUp function to set the favorite color in
2217 test_doctest.txt:
2218
2219 >>> def setUp(test):
2220 ... test.globs['favorite_color'] = 'blue'
2221
2222 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2223 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002224 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002225
2226 Here, we didn't need to use a tearDown function because we
2227 modified the test globals. The test globals are
2228 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002229
Fred Drake7c404a42004-12-21 23:46:34 +00002230 Tests in a file run using `DocFileSuite` can also access the
2231 `__file__` global, which is set to the name of the file
2232 containing the tests:
2233
2234 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2235 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002236 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002237
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002238 If the tests contain non-ASCII characters, we have to specify which
2239 encoding the file is encoded with. We do so by using the `encoding`
2240 parameter:
2241
2242 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2243 ... 'test_doctest2.txt',
2244 ... 'test_doctest4.txt',
2245 ... encoding='utf-8')
2246 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002247 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002248
Jim Fultonf54bad42004-08-28 14:57:56 +00002249 """
Tim Peters19397e52004-08-06 22:02:59 +00002250
Jim Fulton07a349c2004-08-22 14:10:00 +00002251def test_trailing_space_in_test():
2252 """
Tim Petersa7def722004-08-23 22:13:22 +00002253 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002254
Jim Fulton07a349c2004-08-22 14:10:00 +00002255 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002256 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002257 foo \n
2258 """
Tim Peters19397e52004-08-06 22:02:59 +00002259
Jim Fultonf54bad42004-08-28 14:57:56 +00002260
2261def test_unittest_reportflags():
2262 """Default unittest reporting flags can be set to control reporting
2263
2264 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2265 only the first failure of each test. First, we'll look at the
2266 output without the flag. The file test_doctest.txt file has two
2267 tests. They both fail if blank lines are disabled:
2268
2269 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2270 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2271 >>> import unittest
2272 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002273 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002274 Traceback ...
2275 Failed example:
2276 favorite_color
2277 ...
2278 Failed example:
2279 if 1:
2280 ...
2281
2282 Note that we see both failures displayed.
2283
2284 >>> old = doctest.set_unittest_reportflags(
2285 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2286
2287 Now, when we run the test:
2288
2289 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002290 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002291 Traceback ...
2292 Failed example:
2293 favorite_color
2294 Exception raised:
2295 ...
2296 NameError: name 'favorite_color' is not defined
2297 <BLANKLINE>
2298 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002299
Jim Fultonf54bad42004-08-28 14:57:56 +00002300 We get only the first failure.
2301
2302 If we give any reporting options when we set up the tests,
2303 however:
2304
2305 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2306 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2307
2308 Then the default eporting options are ignored:
2309
2310 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002311 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002312 Traceback ...
2313 Failed example:
2314 favorite_color
2315 ...
2316 Failed example:
2317 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002318 print('a')
2319 print()
2320 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002321 Differences (ndiff with -expected +actual):
2322 a
2323 - <BLANKLINE>
2324 +
2325 b
2326 <BLANKLINE>
2327 <BLANKLINE>
2328
2329
2330 Test runners can restore the formatting flags after they run:
2331
2332 >>> ignored = doctest.set_unittest_reportflags(old)
2333
2334 """
2335
Edward Loper052d0cd2004-09-19 17:19:33 +00002336def test_testfile(): r"""
2337Tests for the `testfile()` function. This function runs all the
2338doctest examples in a given file. In its simple invokation, it is
2339called with the name of a file, which is taken to be relative to the
2340calling module. The return value is (#failures, #tests).
2341
Florent Xicluna59250852010-02-27 14:21:57 +00002342We don't want `-v` in sys.argv for these tests.
2343
2344 >>> save_argv = sys.argv
2345 >>> if '-v' in sys.argv:
2346 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2347
2348
Edward Loper052d0cd2004-09-19 17:19:33 +00002349 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2350 **********************************************************************
2351 File "...", line 6, in test_doctest.txt
2352 Failed example:
2353 favorite_color
2354 Exception raised:
2355 ...
2356 NameError: name 'favorite_color' is not defined
2357 **********************************************************************
2358 1 items had failures:
2359 1 of 2 in test_doctest.txt
2360 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002361 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002362 >>> doctest.master = None # Reset master.
2363
2364(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002365`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002366same name.)
2367
2368Globals may be specified with the `globs` and `extraglobs` parameters:
2369
2370 >>> globs = {'favorite_color': 'blue'}
2371 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002372 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002373 >>> doctest.master = None # Reset master.
2374
2375 >>> extraglobs = {'favorite_color': 'red'}
2376 >>> doctest.testfile('test_doctest.txt', globs=globs,
2377 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2378 **********************************************************************
2379 File "...", line 6, in test_doctest.txt
2380 Failed example:
2381 favorite_color
2382 Expected:
2383 'blue'
2384 Got:
2385 'red'
2386 **********************************************************************
2387 1 items had failures:
2388 1 of 2 in test_doctest.txt
2389 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002390 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002391 >>> doctest.master = None # Reset master.
2392
2393The file may be made relative to a given module or package, using the
2394optional `module_relative` parameter:
2395
2396 >>> doctest.testfile('test_doctest.txt', globs=globs,
2397 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002398 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002399 >>> doctest.master = None # Reset master.
2400
Ezio Melotti13925002011-03-16 11:05:33 +02002401Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002402
2403 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2404 Trying:
2405 favorite_color
2406 Expecting:
2407 'blue'
2408 ok
2409 Trying:
2410 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002411 print('a')
2412 print()
2413 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002414 Expecting:
2415 a
2416 <BLANKLINE>
2417 b
2418 ok
2419 1 items passed all tests:
2420 2 tests in test_doctest.txt
2421 2 tests in 1 items.
2422 2 passed and 0 failed.
2423 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002424 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002425 >>> doctest.master = None # Reset master.
2426
2427The name of the test may be specified with the optional `name`
2428parameter:
2429
2430 >>> doctest.testfile('test_doctest.txt', name='newname')
2431 ... # doctest: +ELLIPSIS
2432 **********************************************************************
2433 File "...", line 6, in newname
2434 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002435 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002436 >>> doctest.master = None # Reset master.
2437
Ezio Melotti13925002011-03-16 11:05:33 +02002438The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002439parameter:
2440
2441 >>> doctest.testfile('test_doctest.txt', report=False)
2442 ... # doctest: +ELLIPSIS
2443 **********************************************************************
2444 File "...", line 6, in test_doctest.txt
2445 Failed example:
2446 favorite_color
2447 Exception raised:
2448 ...
2449 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002450 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002451 >>> doctest.master = None # Reset master.
2452
2453The optional keyword argument `raise_on_error` can be used to raise an
2454exception on the first error (which may be useful for postmortem
2455debugging):
2456
2457 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2458 ... # doctest: +ELLIPSIS
2459 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002460 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002461 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002462
2463If the tests contain non-ASCII characters, the tests might fail, since
2464it's unknown which encoding is used. The encoding can be specified
2465using the optional keyword argument `encoding`:
2466
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002467 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002468 **********************************************************************
2469 File "...", line 7, in test_doctest4.txt
2470 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002471 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002472 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002473 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002474 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002475 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002476 **********************************************************************
2477 ...
2478 **********************************************************************
2479 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002480 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002481 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002482 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002483 >>> doctest.master = None # Reset master.
2484
2485 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002486 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002487 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002488
2489Test the verbose output:
2490
2491 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2492 Trying:
2493 'föö'
2494 Expecting:
2495 'f\xf6\xf6'
2496 ok
2497 Trying:
2498 'bąr'
2499 Expecting:
2500 'b\u0105r'
2501 ok
2502 1 items passed all tests:
2503 2 tests in test_doctest4.txt
2504 2 tests in 1 items.
2505 2 passed and 0 failed.
2506 Test passed.
2507 TestResults(failed=0, attempted=2)
2508 >>> doctest.master = None # Reset master.
2509 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002510"""
2511
R. David Murray58641de2009-06-12 15:33:19 +00002512def test_testmod(): r"""
2513Tests for the testmod function. More might be useful, but for now we're just
2514testing the case raised by Issue 6195, where trying to doctest a C module would
2515fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2516out of the binary module.
2517
2518 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002519 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002520 TestResults(failed=0, attempted=0)
2521"""
2522
Victor Stinner9d396392010-10-16 21:54:59 +00002523try:
2524 os.fsencode("foo-bär@baz.py")
2525except UnicodeEncodeError:
2526 # Skip the test: the filesystem encoding is unable to encode the filename
2527 pass
2528else:
2529 def test_unicode(): """
2530Check doctest with a non-ascii filename:
2531
2532 >>> doc = '''
2533 ... >>> raise Exception('clé')
2534 ... '''
2535 ...
2536 >>> parser = doctest.DocTestParser()
2537 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2538 >>> test
2539 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2540 >>> runner = doctest.DocTestRunner(verbose=False)
2541 >>> runner.run(test) # doctest: +ELLIPSIS
2542 **********************************************************************
2543 File "foo-bär@baz.py", line 2, in foo-bär@baz
2544 Failed example:
2545 raise Exception('clé')
2546 Exception raised:
2547 Traceback (most recent call last):
2548 File ...
2549 compileflags, 1), test.globs)
2550 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2551 raise Exception('clé')
2552 Exception: clé
2553 TestResults(failed=1, attempted=1)
2554 """
2555
Tim Peters8485b562004-08-04 18:46:34 +00002556######################################################################
2557## Main
2558######################################################################
2559
2560def test_main():
2561 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002562 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002563 # Check the doctest cases defined here:
2564 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002565 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002566
Victor Stinner45df8202010-04-28 22:31:17 +00002567import sys, re, io
2568
Tim Peters8485b562004-08-04 18:46:34 +00002569def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002570 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01002571 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00002572 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002573 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002574 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002575 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002576 r.write_results(show_missing=True, summary=True,
2577 coverdir=coverdir)
2578
2579if __name__ == '__main__':
2580 if '-c' in sys.argv:
2581 test_coverage('/tmp/doctest.cover')
2582 else:
2583 test_main()