blob: 5969ce2fbe358c3f2cd0f0419b26479f6fa4a9e1 [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
Tim Peters8485b562004-08-04 18:46:34 +00008
Florent Xiclunadc6f2d02010-04-02 19:25:32 +00009
Nick Coghlanf088e5e2008-12-14 11:50:48 +000010# NOTE: There are some additional tests relating to interaction with
11# zipimport in the test_zipimport_support test module.
12
Tim Peters8485b562004-08-04 18:46:34 +000013######################################################################
14## Sample Objects (used by test cases)
15######################################################################
16
17def sample_func(v):
18 """
Tim Peters19397e52004-08-06 22:02:59 +000019 Blah blah
20
Guido van Rossum7131f842007-02-09 20:13:25 +000021 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000022 44
Tim Peters19397e52004-08-06 22:02:59 +000023
24 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000025 """
26 return v+v
27
28class SampleClass:
29 """
Guido van Rossum7131f842007-02-09 20:13:25 +000030 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000031 1
Edward Loper4ae900f2004-09-21 03:20:34 +000032
33 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
34 >>>
35 ...
36
37 Multiline example:
38 >>> sc = SampleClass(3)
39 >>> for i in range(10):
40 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000041 ... print(' ', sc.get(), sep='', end='')
42 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000043 """
44 def __init__(self, val):
45 """
Guido van Rossum7131f842007-02-09 20:13:25 +000046 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000047 12
48 """
49 self.val = val
50
51 def double(self):
52 """
Guido van Rossum7131f842007-02-09 20:13:25 +000053 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000054 24
55 """
56 return SampleClass(self.val + self.val)
57
58 def get(self):
59 """
Guido van Rossum7131f842007-02-09 20:13:25 +000060 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000061 -5
62 """
63 return self.val
64
65 def a_staticmethod(v):
66 """
Guido van Rossum7131f842007-02-09 20:13:25 +000067 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000068 11
69 """
70 return v+1
71 a_staticmethod = staticmethod(a_staticmethod)
72
73 def a_classmethod(cls, v):
74 """
Guido van Rossum7131f842007-02-09 20:13:25 +000075 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000076 12
Guido van Rossum7131f842007-02-09 20:13:25 +000077 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000078 12
79 """
80 return v+2
81 a_classmethod = classmethod(a_classmethod)
82
83 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000084 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000085 22
86 """)
87
88 class NestedClass:
89 """
90 >>> x = SampleClass.NestedClass(5)
91 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000092 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000093 25
94 """
95 def __init__(self, val=0):
96 """
Guido van Rossum7131f842007-02-09 20:13:25 +000097 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +000098 0
99 """
100 self.val = val
101 def square(self):
102 return SampleClass.NestedClass(self.val*self.val)
103 def get(self):
104 return self.val
105
106class SampleNewStyleClass(object):
107 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000108 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000109 1
110 2
111 3
112 """
113 def __init__(self, val):
114 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000115 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000116 12
117 """
118 self.val = val
119
120 def double(self):
121 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000122 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000123 24
124 """
125 return SampleNewStyleClass(self.val + self.val)
126
127 def get(self):
128 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000129 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000130 -5
131 """
132 return self.val
133
134######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000135## Fake stdin (for testing interactive debugging)
136######################################################################
137
138class _FakeInput:
139 """
140 A fake input stream for pdb's interactive debugger. Whenever a
141 line is read, print it (to simulate the user typing it), and then
142 return it. The set of lines to return is specified in the
143 constructor; they should not have trailing newlines.
144 """
145 def __init__(self, lines):
146 self.lines = lines
147
148 def readline(self):
149 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000150 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000151 return line+'\n'
152
153######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000154## Test Cases
155######################################################################
156
157def test_Example(): r"""
158Unit tests for the `Example` class.
159
Edward Lopera6b68322004-08-26 00:05:43 +0000160Example is a simple container class that holds:
161 - `source`: A source string.
162 - `want`: An expected output string.
163 - `exc_msg`: An expected exception message string (or None if no
164 exception is expected).
165 - `lineno`: A line number (within the docstring).
166 - `indent`: The example's indentation in the input string.
167 - `options`: An option dictionary, mapping option flags to True or
168 False.
Tim Peters8485b562004-08-04 18:46:34 +0000169
Edward Lopera6b68322004-08-26 00:05:43 +0000170These attributes are set by the constructor. `source` and `want` are
171required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000172
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000173 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000174 >>> (example.source, example.want, example.exc_msg,
175 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000176 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000177
178The first three attributes (`source`, `want`, and `exc_msg`) may be
179specified positionally; the remaining arguments should be specified as
180keyword arguments:
181
182 >>> exc_msg = 'IndexError: pop from an empty list'
183 >>> example = doctest.Example('[].pop()', '', exc_msg,
184 ... lineno=5, indent=4,
185 ... options={doctest.ELLIPSIS: True})
186 >>> (example.source, example.want, example.exc_msg,
187 ... example.lineno, example.indent, example.options)
188 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
189
190The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000191
Tim Petersbb431472004-08-09 03:51:46 +0000192 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000193 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000194 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000195 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000196
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000197 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000198 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000199 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000200
Tim Petersbb431472004-08-09 03:51:46 +0000201 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000202 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000203 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000204 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000205
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000206 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000207 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000208 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000209
Edward Lopera6b68322004-08-26 00:05:43 +0000210 Empty source string (which should never appear in real examples)
211 >>> e = doctest.Example('', '')
212 >>> e.source, e.want
213 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000214
Edward Lopera6b68322004-08-26 00:05:43 +0000215The constructor normalizes the `want` string to end in a newline,
216unless it's the empty string:
217
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000218 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000219 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000220 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000221
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000222 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000223 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000224 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000225
Edward Lopera6b68322004-08-26 00:05:43 +0000226 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000227 >>> e.source, e.want
228 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000229
230The constructor normalizes the `exc_msg` string to end in a newline,
231unless it's `None`:
232
233 Message spans one line
234 >>> exc_msg = 'IndexError: pop from an empty list'
235 >>> e = doctest.Example('[].pop()', '', exc_msg)
236 >>> e.exc_msg
237 'IndexError: pop from an empty list\n'
238
239 >>> exc_msg = 'IndexError: pop from an empty list\n'
240 >>> e = doctest.Example('[].pop()', '', exc_msg)
241 >>> e.exc_msg
242 'IndexError: pop from an empty list\n'
243
244 Message spans multiple lines
245 >>> exc_msg = 'ValueError: 1\n 2'
246 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
247 >>> e.exc_msg
248 'ValueError: 1\n 2\n'
249
250 >>> exc_msg = 'ValueError: 1\n 2\n'
251 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
252 >>> e.exc_msg
253 'ValueError: 1\n 2\n'
254
255 Empty (but non-None) exception message (which should never appear
256 in real examples)
257 >>> exc_msg = ''
258 >>> e = doctest.Example('raise X()', '', exc_msg)
259 >>> e.exc_msg
260 '\n'
Antoine Pitrou165b1282011-12-18 20:20:17 +0100261
262Compare `Example`:
263 >>> example = doctest.Example('print 1', '1\n')
264 >>> same_example = doctest.Example('print 1', '1\n')
265 >>> other_example = doctest.Example('print 42', '42\n')
266 >>> example == same_example
267 True
268 >>> example != same_example
269 False
270 >>> hash(example) == hash(same_example)
271 True
272 >>> example == other_example
273 False
274 >>> example != other_example
275 True
Tim Peters8485b562004-08-04 18:46:34 +0000276"""
277
278def test_DocTest(): r"""
279Unit tests for the `DocTest` class.
280
281DocTest is a collection of examples, extracted from a docstring, along
282with information about where the docstring comes from (a name,
283filename, and line number). The docstring is parsed by the `DocTest`
284constructor:
285
286 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000287 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000288 ... 12
289 ...
290 ... Non-example text.
291 ...
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000292 ... >>> print('another\example')
Tim Peters8485b562004-08-04 18:46:34 +0000293 ... another
294 ... example
295 ... '''
296 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000297 >>> parser = doctest.DocTestParser()
298 >>> test = parser.get_doctest(docstring, globs, 'some_test',
299 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000300 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000301 <DocTest some_test from some_file:20 (2 examples)>
302 >>> len(test.examples)
303 2
304 >>> e1, e2 = test.examples
305 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000306 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000307 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000308 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000309
310Source information (name, filename, and line number) is available as
311attributes on the doctest object:
312
313 >>> (test.name, test.filename, test.lineno)
314 ('some_test', 'some_file', 20)
315
316The line number of an example within its containing file is found by
317adding the line number of the example and the line number of its
318containing test:
319
320 >>> test.lineno + e1.lineno
321 21
322 >>> test.lineno + e2.lineno
323 26
324
325If the docstring contains inconsistant leading whitespace in the
326expected output of an example, then `DocTest` will raise a ValueError:
327
328 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000329 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000330 ... bad
331 ... indentation
332 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000333 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000334 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000335 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000336
337If the docstring contains inconsistent leading whitespace on
338continuation lines, then `DocTest` will raise a ValueError:
339
340 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000341 ... >>> print(('bad indentation',
342 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000343 ... ('bad', 'indentation')
344 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000345 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000346 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000347 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000348
349If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
350will raise a ValueError:
351
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000352 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000353 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000354 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000355 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000356
357If there's no blank space after a PS2 prompt ('...'), then `DocTest`
358will raise a ValueError:
359
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000360 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000361 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000362 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000363 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000364
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100365Compare `DocTest`:
366
367 >>> docstring = '''
368 ... >>> print 12
369 ... 12
370 ... '''
371 >>> test = parser.get_doctest(docstring, globs, 'some_test',
372 ... 'some_test', 20)
373 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
374 ... 'some_test', 20)
375 >>> test == same_test
376 True
377 >>> test != same_test
378 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100379 >>> hash(test) == hash(same_test)
380 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100381 >>> docstring = '''
382 ... >>> print 42
383 ... 42
384 ... '''
385 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
386 ... 'other_file', 10)
387 >>> test == other_test
388 False
389 >>> test != other_test
390 True
391
392Compare `DocTestCase`:
393
394 >>> DocTestCase = doctest.DocTestCase
395 >>> test_case = DocTestCase(test)
396 >>> same_test_case = DocTestCase(same_test)
397 >>> other_test_case = DocTestCase(other_test)
398 >>> test_case == same_test_case
399 True
400 >>> test_case != same_test_case
401 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100402 >>> hash(test_case) == hash(same_test_case)
403 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100404 >>> test == other_test_case
405 False
406 >>> test != other_test_case
407 True
408
Tim Peters8485b562004-08-04 18:46:34 +0000409"""
410
Tim Peters8485b562004-08-04 18:46:34 +0000411def test_DocTestFinder(): r"""
412Unit tests for the `DocTestFinder` class.
413
414DocTestFinder is used to extract DocTests from an object's docstring
415and the docstrings of its contained objects. It can be used with
416modules, functions, classes, methods, staticmethods, classmethods, and
417properties.
418
419Finding Tests in Functions
420~~~~~~~~~~~~~~~~~~~~~~~~~~
421For a function whose docstring contains examples, DocTestFinder.find()
422will return a single test (for that function's docstring):
423
Tim Peters8485b562004-08-04 18:46:34 +0000424 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000425
426We'll simulate a __file__ attr that ends in pyc:
427
428 >>> import test.test_doctest
429 >>> old = test.test_doctest.__file__
430 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
431
Tim Peters8485b562004-08-04 18:46:34 +0000432 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000433
Guido van Rossum7131f842007-02-09 20:13:25 +0000434 >>> print(tests) # doctest: +ELLIPSIS
Victor Stinner9d396392010-10-16 21:54:59 +0000435 [<DocTest sample_func from ...:17 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000436
Tim Peters4de7c5c2004-08-23 22:38:05 +0000437The exact name depends on how test_doctest was invoked, so allow for
438leading path components.
439
440 >>> tests[0].filename # doctest: +ELLIPSIS
441 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000442
443 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000444
Jim Fulton07a349c2004-08-22 14:10:00 +0000445
Tim Peters8485b562004-08-04 18:46:34 +0000446 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000447 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000448 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000449
Edward Loper32ddbf72004-09-13 05:47:24 +0000450By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000451
452 >>> def no_docstring(v):
453 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000454 >>> finder.find(no_docstring)
455 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000456
457However, the optional argument `exclude_empty` to the DocTestFinder
458constructor can be used to exclude tests for objects with empty
459docstrings:
460
461 >>> def no_docstring(v):
462 ... pass
463 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
464 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000465 []
466
467If the function has a docstring with no examples, then a test with no
468examples is returned. (This lets `DocTestRunner` collect statistics
469about which functions have no tests -- but is that useful? And should
470an empty test also be created when there's no docstring?)
471
472 >>> def no_examples(v):
473 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000474 >>> finder.find(no_examples) # doctest: +ELLIPSIS
475 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000476
477Finding Tests in Classes
478~~~~~~~~~~~~~~~~~~~~~~~~
479For a class, DocTestFinder will create a test for the class's
480docstring, and will recursively explore its contents, including
481methods, classmethods, staticmethods, properties, and nested classes.
482
483 >>> finder = doctest.DocTestFinder()
484 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000485 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000486 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000487 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000488 3 SampleClass.NestedClass
489 1 SampleClass.NestedClass.__init__
490 1 SampleClass.__init__
491 2 SampleClass.a_classmethod
492 1 SampleClass.a_property
493 1 SampleClass.a_staticmethod
494 1 SampleClass.double
495 1 SampleClass.get
496
497New-style classes are also supported:
498
499 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000500 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000501 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000502 1 SampleNewStyleClass
503 1 SampleNewStyleClass.__init__
504 1 SampleNewStyleClass.double
505 1 SampleNewStyleClass.get
506
507Finding Tests in Modules
508~~~~~~~~~~~~~~~~~~~~~~~~
509For a module, DocTestFinder will create a test for the class's
510docstring, and will recursively explore its contents, including
511functions, classes, and the `__test__` dictionary, if it exists:
512
513 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000514 >>> import types
515 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000516 >>> def triple(val):
517 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000518 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000519 ... 33
520 ... '''
521 ... return val*3
522 >>> m.__dict__.update({
523 ... 'sample_func': sample_func,
524 ... 'SampleClass': SampleClass,
525 ... '__doc__': '''
526 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000527 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000528 ... module
529 ... ''',
530 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000531 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000532 ... 'c': triple}})
533
534 >>> finder = doctest.DocTestFinder()
535 >>> # Use module=test.test_doctest, to prevent doctest from
536 >>> # ignoring the objects since they weren't defined in m.
537 >>> import test.test_doctest
538 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000539 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000540 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000541 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000542 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000543 3 some_module.SampleClass.NestedClass
544 1 some_module.SampleClass.NestedClass.__init__
545 1 some_module.SampleClass.__init__
546 2 some_module.SampleClass.a_classmethod
547 1 some_module.SampleClass.a_property
548 1 some_module.SampleClass.a_staticmethod
549 1 some_module.SampleClass.double
550 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000551 1 some_module.__test__.c
552 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000553 1 some_module.sample_func
554
555Duplicate Removal
556~~~~~~~~~~~~~~~~~
557If a single object is listed twice (under different names), then tests
558will only be generated for it once:
559
Tim Petersf3f57472004-08-08 06:11:48 +0000560 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000561 >>> assert doctest_aliases.TwoNames.f
562 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000563 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000564 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000565 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000566 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000567 test.doctest_aliases.TwoNames
568
569 TwoNames.f and TwoNames.g are bound to the same object.
570 We can't guess which will be found in doctest's traversal of
571 TwoNames.__dict__ first, so we have to allow for either.
572
573 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000574 True
575
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000576Empty Tests
577~~~~~~~~~~~
578By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000579
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000580 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000581 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000582 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000583 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000584 3 SampleClass.NestedClass
585 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000586 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000587 2 SampleClass.a_classmethod
588 1 SampleClass.a_property
589 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000590 1 SampleClass.double
591 1 SampleClass.get
592
593By default, that excluded objects with no doctests. exclude_empty=False
594tells it to include (empty) tests for objects with no doctests. This feature
595is really to support backward compatibility in what doctest.master.summarize()
596displays.
597
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000598 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000599 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000600 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000601 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000602 3 SampleClass.NestedClass
603 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000604 0 SampleClass.NestedClass.get
605 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000606 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000607 2 SampleClass.a_classmethod
608 1 SampleClass.a_property
609 1 SampleClass.a_staticmethod
610 1 SampleClass.double
611 1 SampleClass.get
612
Tim Peters8485b562004-08-04 18:46:34 +0000613Turning off Recursion
614~~~~~~~~~~~~~~~~~~~~~
615DocTestFinder can be told not to look for tests in contained objects
616using the `recurse` flag:
617
618 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000619 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000620 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000621 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000622
623Line numbers
624~~~~~~~~~~~~
625DocTestFinder finds the line number of each example:
626
627 >>> def f(x):
628 ... '''
629 ... >>> x = 12
630 ...
631 ... some text
632 ...
633 ... >>> # examples are not created for comments & bare prompts.
634 ... >>>
635 ... ...
636 ...
637 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000638 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000639 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000640 ... >>> x//2
641 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000642 ... '''
643 >>> test = doctest.DocTestFinder().find(f)[0]
644 >>> [e.lineno for e in test.examples]
645 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000646"""
647
Edward Loper00f8da72004-08-26 18:05:07 +0000648def test_DocTestParser(): r"""
649Unit tests for the `DocTestParser` class.
650
651DocTestParser is used to parse docstrings containing doctest examples.
652
653The `parse` method divides a docstring into examples and intervening
654text:
655
656 >>> s = '''
657 ... >>> x, y = 2, 3 # no output expected
658 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000659 ... ... print(x)
660 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000661 ... 2
662 ... 3
663 ...
664 ... Some text.
665 ... >>> x+y
666 ... 5
667 ... '''
668 >>> parser = doctest.DocTestParser()
669 >>> for piece in parser.parse(s):
670 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000671 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000672 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000673 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000674 Text: '\n'
675 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
676 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000677 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000678 Text: '\nSome text.\n'
679 Example: ('x+y\n', '5\n', 9)
680 Text: ''
681
682The `get_examples` method returns just the examples:
683
684 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000685 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000686 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000687 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000688 ('x+y\n', '5\n', 9)
689
690The `get_doctest` method creates a Test from the examples, along with the
691given arguments:
692
693 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
694 >>> (test.name, test.filename, test.lineno)
695 ('name', 'filename', 5)
696 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000697 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000698 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000699 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000700 ('x+y\n', '5\n', 9)
701"""
702
Tim Peters8485b562004-08-04 18:46:34 +0000703class test_DocTestRunner:
704 def basics(): r"""
705Unit tests for the `DocTestRunner` class.
706
707DocTestRunner is used to run DocTest test cases, and to accumulate
708statistics. Here's a simple DocTest case we can use:
709
710 >>> def f(x):
711 ... '''
712 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000713 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000714 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000715 ... >>> x//2
716 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000717 ... '''
718 >>> test = doctest.DocTestFinder().find(f)[0]
719
720The main DocTestRunner interface is the `run` method, which runs a
721given DocTest case in a given namespace (globs). It returns a tuple
722`(f,t)`, where `f` is the number of failed tests and `t` is the number
723of tried tests.
724
725 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000726 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000727
728If any example produces incorrect output, then the test runner reports
729the failure and proceeds to the next example:
730
731 >>> def f(x):
732 ... '''
733 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000734 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000735 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000736 ... >>> x//2
737 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000738 ... '''
739 >>> test = doctest.DocTestFinder().find(f)[0]
740 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000741 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000742 Trying:
743 x = 12
744 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000745 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000746 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000747 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000748 Expecting:
749 14
Tim Peters8485b562004-08-04 18:46:34 +0000750 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000751 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000752 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000753 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000754 Expected:
755 14
756 Got:
757 12
Edward Loperaacf0832004-08-26 01:19:50 +0000758 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000759 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000760 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000761 6
Tim Peters8485b562004-08-04 18:46:34 +0000762 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000763 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000764"""
765 def verbose_flag(): r"""
766The `verbose` flag makes the test runner generate more detailed
767output:
768
769 >>> def f(x):
770 ... '''
771 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000772 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000773 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000774 ... >>> x//2
775 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000776 ... '''
777 >>> test = doctest.DocTestFinder().find(f)[0]
778
779 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000780 Trying:
781 x = 12
782 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000783 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000784 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000785 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000786 Expecting:
787 12
Tim Peters8485b562004-08-04 18:46:34 +0000788 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000789 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000790 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000791 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000792 6
Tim Peters8485b562004-08-04 18:46:34 +0000793 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000794 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000795
796If the `verbose` flag is unspecified, then the output will be verbose
797iff `-v` appears in sys.argv:
798
799 >>> # Save the real sys.argv list.
800 >>> old_argv = sys.argv
801
802 >>> # If -v does not appear in sys.argv, then output isn't verbose.
803 >>> sys.argv = ['test']
804 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000805 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000806
807 >>> # If -v does appear in sys.argv, then output is verbose.
808 >>> sys.argv = ['test', '-v']
809 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000810 Trying:
811 x = 12
812 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000813 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000814 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000815 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000816 Expecting:
817 12
Tim Peters8485b562004-08-04 18:46:34 +0000818 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000819 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000820 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000821 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000822 6
Tim Peters8485b562004-08-04 18:46:34 +0000823 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000824 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000825
826 >>> # Restore sys.argv
827 >>> sys.argv = old_argv
828
829In the remaining examples, the test runner's verbosity will be
830explicitly set, to ensure that the test behavior is consistent.
831 """
832 def exceptions(): r"""
833Tests of `DocTestRunner`'s exception handling.
834
835An expected exception is specified with a traceback message. The
836lines between the first line and the type/value may be omitted or
837replaced with any other string:
838
839 >>> def f(x):
840 ... '''
841 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000842 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000843 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000844 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000845 ... '''
846 >>> test = doctest.DocTestFinder().find(f)[0]
847 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000848 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000849
Edward Loper19b19582004-08-25 23:07:03 +0000850An example may not generate output before it raises an exception; if
851it does, then the traceback message will not be recognized as
852signaling an expected exception, so the example will be reported as an
853unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000854
855 >>> def f(x):
856 ... '''
857 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000858 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000859 ... pre-exception output
860 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000861 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000862 ... '''
863 >>> test = doctest.DocTestFinder().find(f)[0]
864 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000865 ... # doctest: +ELLIPSIS
866 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000867 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000868 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000869 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000870 Exception raised:
871 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000872 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000873 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000874
875Exception messages may contain newlines:
876
877 >>> def f(x):
878 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000879 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000880 ... Traceback (most recent call last):
881 ... ValueError: multi
882 ... line
883 ... message
884 ... '''
885 >>> test = doctest.DocTestFinder().find(f)[0]
886 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000887 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000888
889If an exception is expected, but an exception with the wrong type or
890message is raised, then it is reported as a failure:
891
892 >>> def f(x):
893 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000894 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000895 ... Traceback (most recent call last):
896 ... ValueError: wrong message
897 ... '''
898 >>> test = doctest.DocTestFinder().find(f)[0]
899 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000900 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000901 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000902 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000903 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000904 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000905 Expected:
906 Traceback (most recent call last):
907 ValueError: wrong message
908 Got:
909 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000910 ...
Tim Peters8485b562004-08-04 18:46:34 +0000911 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000912 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000913
Tim Peters1fbf9c52004-09-04 17:21:02 +0000914However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
915detail:
916
917 >>> def f(x):
918 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000919 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000920 ... Traceback (most recent call last):
921 ... ValueError: wrong message
922 ... '''
923 >>> test = doctest.DocTestFinder().find(f)[0]
924 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000925 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000926
Nick Coghlan5e76e942010-06-12 13:42:46 +0000927IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
928between Python versions. For example, in Python 2.x, the module path of
929the exception is not in the output, but this will fail under Python 3:
930
931 >>> def f(x):
932 ... r'''
933 ... >>> from http.client import HTTPException
934 ... >>> raise HTTPException('message')
935 ... Traceback (most recent call last):
936 ... HTTPException: message
937 ... '''
938 >>> test = doctest.DocTestFinder().find(f)[0]
939 >>> doctest.DocTestRunner(verbose=False).run(test)
940 ... # doctest: +ELLIPSIS
941 **********************************************************************
942 File ..., line 4, in f
943 Failed example:
944 raise HTTPException('message')
945 Expected:
946 Traceback (most recent call last):
947 HTTPException: message
948 Got:
949 Traceback (most recent call last):
950 ...
951 http.client.HTTPException: message
952 TestResults(failed=1, attempted=2)
953
954But in Python 3 the module path is included, and therefore a test must look
955like the following test to succeed in Python 3. But that test will fail under
956Python 2.
957
958 >>> def f(x):
959 ... r'''
960 ... >>> from http.client import HTTPException
961 ... >>> raise HTTPException('message')
962 ... Traceback (most recent call last):
963 ... http.client.HTTPException: message
964 ... '''
965 >>> test = doctest.DocTestFinder().find(f)[0]
966 >>> doctest.DocTestRunner(verbose=False).run(test)
967 TestResults(failed=0, attempted=2)
968
969However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
970(or its unexpected absence) will be ignored:
971
972 >>> def f(x):
973 ... r'''
974 ... >>> from http.client import HTTPException
975 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
976 ... Traceback (most recent call last):
977 ... HTTPException: message
978 ... '''
979 >>> test = doctest.DocTestFinder().find(f)[0]
980 >>> doctest.DocTestRunner(verbose=False).run(test)
981 TestResults(failed=0, attempted=2)
982
983The module path will be completely ignored, so two different module paths will
984still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
985be used when exceptions have changed module.
986
987 >>> def f(x):
988 ... r'''
989 ... >>> from http.client import HTTPException
990 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
991 ... Traceback (most recent call last):
992 ... foo.bar.HTTPException: message
993 ... '''
994 >>> test = doctest.DocTestFinder().find(f)[0]
995 >>> doctest.DocTestRunner(verbose=False).run(test)
996 TestResults(failed=0, attempted=2)
997
Tim Peters1fbf9c52004-09-04 17:21:02 +0000998But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
999
1000 >>> def f(x):
1001 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001002 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001003 ... Traceback (most recent call last):
1004 ... TypeError: wrong type
1005 ... '''
1006 >>> test = doctest.DocTestFinder().find(f)[0]
1007 >>> doctest.DocTestRunner(verbose=False).run(test)
1008 ... # doctest: +ELLIPSIS
1009 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001010 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001011 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001012 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001013 Expected:
1014 Traceback (most recent call last):
1015 TypeError: wrong type
1016 Got:
1017 Traceback (most recent call last):
1018 ...
1019 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001020 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001021
Tim Peters8485b562004-08-04 18:46:34 +00001022If an exception is raised but not expected, then it is reported as an
1023unexpected exception:
1024
Tim Peters8485b562004-08-04 18:46:34 +00001025 >>> def f(x):
1026 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001027 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001028 ... 0
1029 ... '''
1030 >>> test = doctest.DocTestFinder().find(f)[0]
1031 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001032 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001033 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001034 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001035 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001036 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001037 Exception raised:
1038 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001039 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001040 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001041 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001042"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001043 def displayhook(): r"""
1044Test that changing sys.displayhook doesn't matter for doctest.
1045
1046 >>> import sys
1047 >>> orig_displayhook = sys.displayhook
1048 >>> def my_displayhook(x):
1049 ... print('hi!')
1050 >>> sys.displayhook = my_displayhook
1051 >>> def f():
1052 ... '''
1053 ... >>> 3
1054 ... 3
1055 ... '''
1056 >>> test = doctest.DocTestFinder().find(f)[0]
1057 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1058 >>> post_displayhook = sys.displayhook
1059
1060 We need to restore sys.displayhook now, so that we'll be able to test
1061 results.
1062
1063 >>> sys.displayhook = orig_displayhook
1064
1065 Ok, now we can check that everything is ok.
1066
1067 >>> r
1068 TestResults(failed=0, attempted=1)
1069 >>> post_displayhook is my_displayhook
1070 True
1071"""
Tim Peters8485b562004-08-04 18:46:34 +00001072 def optionflags(): r"""
1073Tests of `DocTestRunner`'s option flag handling.
1074
1075Several option flags can be used to customize the behavior of the test
1076runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001077to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001078together).
1079
1080The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1081and 1/0:
1082
1083 >>> def f(x):
1084 ... '>>> True\n1\n'
1085
1086 >>> # Without the flag:
1087 >>> test = doctest.DocTestFinder().find(f)[0]
1088 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001089 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001090
1091 >>> # With the flag:
1092 >>> test = doctest.DocTestFinder().find(f)[0]
1093 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1094 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001095 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001096 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001097 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001098 Failed example:
1099 True
1100 Expected:
1101 1
1102 Got:
1103 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001104 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001105
1106The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1107and the '<BLANKLINE>' marker:
1108
1109 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001110 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001111
1112 >>> # Without the flag:
1113 >>> test = doctest.DocTestFinder().find(f)[0]
1114 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001115 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001116
1117 >>> # With the flag:
1118 >>> test = doctest.DocTestFinder().find(f)[0]
1119 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1120 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001121 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001122 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001123 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001124 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001125 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001126 Expected:
1127 a
1128 <BLANKLINE>
1129 b
1130 Got:
1131 a
1132 <BLANKLINE>
1133 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001134 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001135
1136The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1137treated as equal:
1138
1139 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001140 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001141
1142 >>> # Without the flag:
1143 >>> test = doctest.DocTestFinder().find(f)[0]
1144 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001145 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001146 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001147 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001148 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001149 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001150 Expected:
1151 1 2
1152 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001153 Got:
1154 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001155 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001156
1157 >>> # With the flag:
1158 >>> test = doctest.DocTestFinder().find(f)[0]
1159 >>> flags = doctest.NORMALIZE_WHITESPACE
1160 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001161 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001162
Tim Peters026f8dc2004-08-19 16:38:58 +00001163 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001164 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001165 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1166 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1167
Tim Peters8485b562004-08-04 18:46:34 +00001168The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1169output to match any substring in the actual output:
1170
1171 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001172 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001173
1174 >>> # Without the flag:
1175 >>> test = doctest.DocTestFinder().find(f)[0]
1176 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001177 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001178 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001179 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001180 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001181 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001182 Expected:
1183 [0, 1, 2, ..., 14]
1184 Got:
1185 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001186 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001187
1188 >>> # With the flag:
1189 >>> test = doctest.DocTestFinder().find(f)[0]
1190 >>> flags = doctest.ELLIPSIS
1191 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001192 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001193
Tim Peterse594bee2004-08-22 01:47:51 +00001194 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001195
Guido van Rossume0192e52007-02-09 23:39:59 +00001196 >>> if 1:
1197 ... for i in range(100):
1198 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1199 ... print('!')
1200 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001201
Tim Peters026f8dc2004-08-19 16:38:58 +00001202 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001203
Guido van Rossume0192e52007-02-09 23:39:59 +00001204 >>> if 1: #doctest: +ELLIPSIS
1205 ... for i in range(20):
1206 ... print(i, end=' ')
1207 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001208 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001209
Tim Peters026f8dc2004-08-19 16:38:58 +00001210 Examples from the docs:
1211
Guido van Rossum805365e2007-05-07 22:24:25 +00001212 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001213 [0, 1, ..., 18, 19]
1214
Guido van Rossum805365e2007-05-07 22:24:25 +00001215 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001216 ... # doctest: +NORMALIZE_WHITESPACE
1217 [0, 1, ..., 18, 19]
1218
Thomas Wouters477c8d52006-05-27 19:21:47 +00001219The SKIP flag causes an example to be skipped entirely. I.e., the
1220example is not run. It can be useful in contexts where doctest
1221examples serve as both documentation and test cases, and an example
1222should be included for documentation purposes, but should not be
1223checked (e.g., because its output is random, or depends on resources
1224which would be unavailable.) The SKIP flag can also be used for
1225'commenting out' broken examples.
1226
1227 >>> import unavailable_resource # doctest: +SKIP
1228 >>> unavailable_resource.do_something() # doctest: +SKIP
1229 >>> unavailable_resource.blow_up() # doctest: +SKIP
1230 Traceback (most recent call last):
1231 ...
1232 UncheckedBlowUpError: Nobody checks me.
1233
1234 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001235 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001236 0.721216923889
1237
Edward Loper71f55af2004-08-26 01:41:51 +00001238The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001239and actual outputs to be displayed using a unified diff:
1240
1241 >>> def f(x):
1242 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001243 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001244 ... a
1245 ... B
1246 ... c
1247 ... d
1248 ... f
1249 ... g
1250 ... h
1251 ... '''
1252
1253 >>> # Without the flag:
1254 >>> test = doctest.DocTestFinder().find(f)[0]
1255 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001256 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001257 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001258 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001259 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001260 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001261 Expected:
1262 a
1263 B
1264 c
1265 d
1266 f
1267 g
1268 h
1269 Got:
1270 a
1271 b
1272 c
1273 d
1274 e
1275 f
1276 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001277 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001278
1279 >>> # With the flag:
1280 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001281 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001282 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001283 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001284 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001285 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001286 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001287 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001288 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001289 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001290 a
1291 -B
1292 +b
1293 c
1294 d
1295 +e
1296 f
1297 g
1298 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001299 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001300
Edward Loper71f55af2004-08-26 01:41:51 +00001301The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001302and actual outputs to be displayed using a context diff:
1303
Edward Loper71f55af2004-08-26 01:41:51 +00001304 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001305 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001306 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001307 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001308 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001309 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001310 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001311 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001312 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001313 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001314 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001315 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001316 a
1317 ! B
1318 c
1319 d
1320 f
1321 g
1322 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001323 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001324 a
1325 ! b
1326 c
1327 d
1328 + e
1329 f
1330 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001331 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001332
1333
Edward Loper71f55af2004-08-26 01:41:51 +00001334The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001335used by the popular ndiff.py utility. This does intraline difference
1336marking, as well as interline differences.
1337
1338 >>> def f(x):
1339 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001340 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001341 ... a b c d e f g h i j k 1 m
1342 ... '''
1343 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001344 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001345 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001346 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001347 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001348 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001349 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001350 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001351 Differences (ndiff with -expected +actual):
1352 - a b c d e f g h i j k 1 m
1353 ? ^
1354 + a b c d e f g h i j k l m
1355 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001356 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001357
Ezio Melotti13925002011-03-16 11:05:33 +02001358The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001359failing example:
1360
1361 >>> def f(x):
1362 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001363 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001364 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001365 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001366 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001367 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001368 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001369 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001370 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001371 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001372 ... 500
1373 ... '''
1374 >>> test = doctest.DocTestFinder().find(f)[0]
1375 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1376 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001377 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001378 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001379 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001380 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001381 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001382 Expected:
1383 200
1384 Got:
1385 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001386 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001387
Ezio Melotti13925002011-03-16 11:05:33 +02001388However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001389
1390 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001391 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001392 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001393 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001394 Expecting:
1395 1
1396 ok
1397 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001398 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001399 Expecting:
1400 200
1401 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001402 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001403 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001404 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001405 Expected:
1406 200
1407 Got:
1408 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001409 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001410
1411For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1412count as failures:
1413
1414 >>> def f(x):
1415 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001416 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001417 ... 1
1418 ... >>> raise ValueError(2) # first failure
1419 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001420 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001421 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001422 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001423 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001424 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001425 ... 500
1426 ... '''
1427 >>> test = doctest.DocTestFinder().find(f)[0]
1428 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1429 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1430 ... # doctest: +ELLIPSIS
1431 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001432 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001433 Failed example:
1434 raise ValueError(2) # first failure
1435 Exception raised:
1436 ...
1437 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001438 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001439
Thomas Wouters477c8d52006-05-27 19:21:47 +00001440New option flags can also be registered, via register_optionflag(). Here
1441we reach into doctest's internals a bit.
1442
1443 >>> unlikely = "UNLIKELY_OPTION_NAME"
1444 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1445 False
1446 >>> new_flag_value = doctest.register_optionflag(unlikely)
1447 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1448 True
1449
1450Before 2.4.4/2.5, registering a name more than once erroneously created
1451more than one flag value. Here we verify that's fixed:
1452
1453 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1454 >>> redundant_flag_value == new_flag_value
1455 True
1456
1457Clean up.
1458 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1459
Tim Petersc6cbab02004-08-22 19:43:28 +00001460 """
1461
Tim Peters8485b562004-08-04 18:46:34 +00001462 def option_directives(): r"""
1463Tests of `DocTestRunner`'s option directive mechanism.
1464
Edward Loper74bca7a2004-08-12 02:27:44 +00001465Option directives can be used to turn option flags on or off for a
1466single example. To turn an option on for an example, follow that
1467example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001468
1469 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001470 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001471 ... [0, 1, ..., 9]
1472 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001473 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001474 ... [0, 1, ..., 9]
1475 ... '''
1476 >>> test = doctest.DocTestFinder().find(f)[0]
1477 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001478 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001479 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001480 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001481 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001482 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001483 Expected:
1484 [0, 1, ..., 9]
1485 Got:
1486 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001487 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001488
1489To turn an option off for an example, follow that example with a
1490comment of the form ``# doctest: -OPTION``:
1491
1492 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001493 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001494 ... [0, 1, ..., 9]
1495 ...
1496 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001497 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001498 ... [0, 1, ..., 9]
1499 ... '''
1500 >>> test = doctest.DocTestFinder().find(f)[0]
1501 >>> doctest.DocTestRunner(verbose=False,
1502 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001503 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001504 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001505 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001506 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001507 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001508 Expected:
1509 [0, 1, ..., 9]
1510 Got:
1511 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001512 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001513
1514Option directives affect only the example that they appear with; they
1515do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001516
Edward Loper74bca7a2004-08-12 02:27:44 +00001517 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001518 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001519 ... [0, 1, ..., 9]
1520 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001521 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001522 ... [0, 1, ..., 9]
1523 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001524 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001525 ... [0, 1, ..., 9]
1526 ... '''
1527 >>> test = doctest.DocTestFinder().find(f)[0]
1528 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001529 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001530 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001531 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001532 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001533 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001534 Expected:
1535 [0, 1, ..., 9]
1536 Got:
1537 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001538 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001539 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001540 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001541 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001542 Expected:
1543 [0, 1, ..., 9]
1544 Got:
1545 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001546 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001547
Edward Loper74bca7a2004-08-12 02:27:44 +00001548Multiple options may be modified by a single option directive. They
1549may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001550
1551 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001552 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001553 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001554 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001555 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001556 ... [0, 1, ..., 9]
1557 ... '''
1558 >>> test = doctest.DocTestFinder().find(f)[0]
1559 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001560 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001561 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001562 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001563 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001564 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001565 Expected:
1566 [0, 1, ..., 9]
1567 Got:
1568 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001569 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001570
1571 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001572 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001573 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001574 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001575 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1576 ... [0, 1, ..., 9]
1577 ... '''
1578 >>> test = doctest.DocTestFinder().find(f)[0]
1579 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001580 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001581 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001582 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001583 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001584 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001585 Expected:
1586 [0, 1, ..., 9]
1587 Got:
1588 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001589 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001590
1591 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001592 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001593 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001594 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001595 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1596 ... [0, 1, ..., 9]
1597 ... '''
1598 >>> test = doctest.DocTestFinder().find(f)[0]
1599 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001600 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001601 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001602 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001603 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001604 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001605 Expected:
1606 [0, 1, ..., 9]
1607 Got:
1608 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001609 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001610
1611The option directive may be put on the line following the source, as
1612long as a continuation prompt is used:
1613
1614 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001615 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001616 ... ... # doctest: +ELLIPSIS
1617 ... [0, 1, ..., 9]
1618 ... '''
1619 >>> test = doctest.DocTestFinder().find(f)[0]
1620 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001621 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001622
Edward Loper74bca7a2004-08-12 02:27:44 +00001623For examples with multi-line source, the option directive may appear
1624at the end of any line:
1625
1626 >>> def f(x): r'''
1627 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001628 ... ... print(' ', x, end='', sep='')
1629 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001630 ...
1631 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001632 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1633 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001634 ... '''
1635 >>> test = doctest.DocTestFinder().find(f)[0]
1636 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001637 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001638
1639If more than one line of an example with multi-line source has an
1640option directive, then they are combined:
1641
1642 >>> def f(x): r'''
1643 ... Should fail (option directive not on the last line):
1644 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001645 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001646 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001647 ... '''
1648 >>> test = doctest.DocTestFinder().find(f)[0]
1649 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001650 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001651
1652It is an error to have a comment of the form ``# doctest:`` that is
1653*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1654``OPTION`` is an option that has been registered with
1655`register_option`:
1656
1657 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001658 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001659 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1660 Traceback (most recent call last):
1661 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1662
1663 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001664 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001665 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1666 Traceback (most recent call last):
1667 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1668
1669It is an error to use an option directive on a line that contains no
1670source:
1671
1672 >>> s = '>>> # doctest: +ELLIPSIS'
1673 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1674 Traceback (most recent call last):
1675 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 +00001676"""
1677
1678def test_testsource(): r"""
1679Unit tests for `testsource()`.
1680
1681The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001682test with that name in that module, and converts it to a script. The
1683example code is converted to regular Python code. The surrounding
1684words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001685
1686 >>> import test.test_doctest
1687 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001688 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001689 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001690 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001691 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001692 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001693 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001694 #
Edward Lopera5db6002004-08-12 02:41:30 +00001695 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001696 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001697
1698 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001699 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001700 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001701 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001702 ## 1
1703 ## 2
1704 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001705 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001706
1707 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001708 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001709 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001710 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001711 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001712 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001713 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001714 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001715 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001716"""
1717
1718def test_debug(): r"""
1719
1720Create a docstring that we want to debug:
1721
1722 >>> s = '''
1723 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001724 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001725 ... 12
1726 ... '''
1727
1728Create some fake stdin input, to feed to the debugger:
1729
Tim Peters8485b562004-08-04 18:46:34 +00001730 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001731 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001732
1733Run the debugger on the docstring, and then restore sys.stdin.
1734
Edward Loper2de91ba2004-08-27 02:07:46 +00001735 >>> try: doctest.debug_src(s)
1736 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001737 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001738 (Pdb) next
1739 12
Tim Peters8485b562004-08-04 18:46:34 +00001740 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001741 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001742 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001743 12
1744 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001745
1746"""
1747
Jim Fulton356fd192004-08-09 11:34:47 +00001748def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001749 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001750
Tim Peters413ced62004-08-09 15:43:47 +00001751 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001752 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001753 you use it. The doctest module changes sys.stdout so that it can
1754 capture program output. It also temporarily replaces pdb.set_trace
1755 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001756 see debugger output.
1757
1758 >>> doc = '''
1759 ... >>> x = 42
Florent Xicluna35049442010-10-14 21:35:58 +00001760 ... >>> raise Exception('clé')
1761 ... Traceback (most recent call last):
1762 ... Exception: clé
Jim Fulton356fd192004-08-09 11:34:47 +00001763 ... >>> import pdb; pdb.set_trace()
1764 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001765 >>> parser = doctest.DocTestParser()
Victor Stinner9d396392010-10-16 21:54:59 +00001766 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001767 >>> runner = doctest.DocTestRunner(verbose=False)
1768
1769 To demonstrate this, we'll create a fake standard input that
1770 captures our debugger input:
1771
1772 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001773 >>> real_stdin = sys.stdin
1774 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001775 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001776 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001777 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001778
Edward Loper2de91ba2004-08-27 02:07:46 +00001779 >>> try: runner.run(test)
1780 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001781 --Return--
Victor Stinner9d396392010-10-16 21:54:59 +00001782 > <doctest foo-bar@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001783 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001784 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001785 42
1786 (Pdb) continue
Florent Xicluna35049442010-10-14 21:35:58 +00001787 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001788
1789 You can also put pdb.set_trace in a function called from a test:
1790
1791 >>> def calls_set_trace():
1792 ... y=2
1793 ... import pdb; pdb.set_trace()
1794
1795 >>> doc = '''
1796 ... >>> x=1
1797 ... >>> calls_set_trace()
1798 ... '''
Victor Stinner9d396392010-10-16 21:54:59 +00001799 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001800 >>> real_stdin = sys.stdin
1801 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001802 ... 'print(y)', # print data defined in the function
Jim Fulton356fd192004-08-09 11:34:47 +00001803 ... 'up', # out of function
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001804 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001805 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001806 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001807
Tim Peters50c6bdb2004-11-08 22:07:37 +00001808 >>> try:
1809 ... runner.run(test)
1810 ... finally:
1811 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001812 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001813 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1814 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001815 (Pdb) print(y)
Edward Loper2de91ba2004-08-27 02:07:46 +00001816 2
1817 (Pdb) up
Victor Stinner9d396392010-10-16 21:54:59 +00001818 > <doctest foo-bar@baz[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001819 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001820 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001821 1
1822 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001823 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001824
1825 During interactive debugging, source code is shown, even for
1826 doctest examples:
1827
1828 >>> doc = '''
1829 ... >>> def f(x):
1830 ... ... g(x*2)
1831 ... >>> def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001832 ... ... print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001833 ... ... import pdb; pdb.set_trace()
1834 ... >>> f(3)
1835 ... '''
Victor Stinner9d396392010-10-16 21:54:59 +00001836 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001837 >>> real_stdin = sys.stdin
1838 >>> sys.stdin = _FakeInput([
1839 ... 'list', # list source from example 2
1840 ... 'next', # return from g()
1841 ... 'list', # list source from example 1
1842 ... 'next', # return from f()
1843 ... 'list', # list source from example 3
1844 ... 'continue', # stop debugging
1845 ... ''])
1846 >>> try: runner.run(test)
1847 ... finally: sys.stdin = real_stdin
1848 ... # doctest: +NORMALIZE_WHITESPACE
1849 --Return--
Victor Stinner9d396392010-10-16 21:54:59 +00001850 > <doctest foo-bar@baz[1]>(3)g()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001851 -> import pdb; pdb.set_trace()
1852 (Pdb) list
1853 1 def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001854 2 print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001855 3 -> import pdb; pdb.set_trace()
1856 [EOF]
1857 (Pdb) next
1858 --Return--
Victor Stinner9d396392010-10-16 21:54:59 +00001859 > <doctest foo-bar@baz[0]>(2)f()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001860 -> g(x*2)
1861 (Pdb) list
1862 1 def f(x):
1863 2 -> g(x*2)
1864 [EOF]
1865 (Pdb) next
1866 --Return--
Victor Stinner9d396392010-10-16 21:54:59 +00001867 > <doctest foo-bar@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001868 -> f(3)
1869 (Pdb) list
1870 1 -> f(3)
1871 [EOF]
1872 (Pdb) continue
1873 **********************************************************************
Victor Stinner9d396392010-10-16 21:54:59 +00001874 File "foo-bar@baz.py", line 7, in foo-bar@baz
Edward Loper2de91ba2004-08-27 02:07:46 +00001875 Failed example:
1876 f(3)
1877 Expected nothing
1878 Got:
1879 9
Christian Heimes25bb7832008-01-11 16:17:00 +00001880 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001881 """
1882
Tim Peters50c6bdb2004-11-08 22:07:37 +00001883def test_pdb_set_trace_nested():
1884 """This illustrates more-demanding use of set_trace with nested functions.
1885
1886 >>> class C(object):
1887 ... def calls_set_trace(self):
1888 ... y = 1
1889 ... import pdb; pdb.set_trace()
1890 ... self.f1()
1891 ... y = 2
1892 ... def f1(self):
1893 ... x = 1
1894 ... self.f2()
1895 ... x = 2
1896 ... def f2(self):
1897 ... z = 1
1898 ... z = 2
1899
1900 >>> calls_set_trace = C().calls_set_trace
1901
1902 >>> doc = '''
1903 ... >>> a = 1
1904 ... >>> calls_set_trace()
1905 ... '''
1906 >>> parser = doctest.DocTestParser()
1907 >>> runner = doctest.DocTestRunner(verbose=False)
Victor Stinner9d396392010-10-16 21:54:59 +00001908 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001909 >>> real_stdin = sys.stdin
1910 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001911 ... 'print(y)', # print data defined in the function
1912 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1913 ... 'up', 'print(x)',
1914 ... 'up', 'print(y)',
1915 ... 'up', 'print(foo)',
Tim Peters50c6bdb2004-11-08 22:07:37 +00001916 ... 'continue', # stop debugging
1917 ... ''])
1918
1919 >>> try:
1920 ... runner.run(test)
1921 ... finally:
1922 ... sys.stdin = real_stdin
Guido van Rossum4a625c32007-09-08 16:05:25 +00001923 ... # doctest: +REPORT_NDIFF
Tim Peters50c6bdb2004-11-08 22:07:37 +00001924 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1925 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001926 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001927 1
1928 (Pdb) step
1929 --Call--
1930 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1931 -> def f1(self):
1932 (Pdb) step
1933 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1934 -> x = 1
1935 (Pdb) step
1936 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1937 -> self.f2()
1938 (Pdb) step
1939 --Call--
1940 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1941 -> def f2(self):
1942 (Pdb) step
1943 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1944 -> z = 1
1945 (Pdb) step
1946 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1947 -> z = 2
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001948 (Pdb) print(z)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001949 1
1950 (Pdb) up
1951 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1952 -> self.f2()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001953 (Pdb) print(x)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001954 1
1955 (Pdb) up
1956 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1957 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001958 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001959 1
1960 (Pdb) up
Victor Stinner9d396392010-10-16 21:54:59 +00001961 > <doctest foo-bar@baz[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001962 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001963 (Pdb) print(foo)
Georg Brandl0d089622010-07-30 16:00:46 +00001964 *** NameError: name 'foo' is not defined
Tim Peters50c6bdb2004-11-08 22:07:37 +00001965 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001966 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001967"""
1968
Tim Peters19397e52004-08-06 22:02:59 +00001969def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001970 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001971
1972 We create a Suite by providing a module. A module can be provided
1973 by passing a module object:
1974
1975 >>> import unittest
1976 >>> import test.sample_doctest
1977 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1978 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001979 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001980
1981 We can also supply the module by name:
1982
1983 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1984 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001985 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001986
1987 We can use the current module:
1988
1989 >>> suite = test.sample_doctest.test_suite()
1990 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001991 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001992
1993 We can supply global variables. If we pass globs, they will be
1994 used instead of the module globals. Here we'll pass an empty
1995 globals, triggering an extra error:
1996
1997 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1998 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001999 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002000
2001 Alternatively, we can provide extra globals. Here we'll make an
2002 error go away by providing an extra global variable:
2003
2004 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2005 ... extraglobs={'y': 1})
2006 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002007 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002008
2009 You can pass option flags. Here we'll cause an extra error
2010 by disabling the blank-line feature:
2011
2012 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002013 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002014 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002015 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002016
Tim Peters1e277ee2004-08-07 05:37:52 +00002017 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002018
Jim Fultonf54bad42004-08-28 14:57:56 +00002019 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002020 ... import test.test_doctest
2021 ... test.test_doctest.sillySetup = True
2022
Jim Fultonf54bad42004-08-28 14:57:56 +00002023 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002024 ... import test.test_doctest
2025 ... del test.test_doctest.sillySetup
2026
2027 Here, we installed a silly variable that the test expects:
2028
2029 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2030 ... setUp=setUp, tearDown=tearDown)
2031 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002032 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002033
2034 But the tearDown restores sanity:
2035
2036 >>> import test.test_doctest
2037 >>> test.test_doctest.sillySetup
2038 Traceback (most recent call last):
2039 ...
2040 AttributeError: 'module' object has no attribute 'sillySetup'
2041
Jim Fultonf54bad42004-08-28 14:57:56 +00002042 The setUp and tearDown funtions are passed test objects. Here
2043 we'll use the setUp function to supply the missing variable y:
2044
2045 >>> def setUp(test):
2046 ... test.globs['y'] = 1
2047
2048 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2049 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002050 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002051
2052 Here, we didn't need to use a tearDown function because we
2053 modified the test globals, which are a copy of the
2054 sample_doctest module dictionary. The test globals are
2055 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002056 """
2057
2058def test_DocFileSuite():
2059 """We can test tests found in text files using a DocFileSuite.
2060
2061 We create a suite by providing the names of one or more text
2062 files that include examples:
2063
2064 >>> import unittest
2065 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002066 ... 'test_doctest2.txt',
2067 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002068 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002069 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002070
2071 The test files are looked for in the directory containing the
2072 calling module. A package keyword argument can be provided to
2073 specify a different relative location.
2074
2075 >>> import unittest
2076 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2077 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002078 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002079 ... package='test')
2080 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002081 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002082
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002083 Support for using a package's __loader__.get_data() is also
2084 provided.
2085
2086 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002087 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002088 >>> if not hasattr(test, '__loader__'):
2089 ... test.__loader__ = pkgutil.get_loader(test)
2090 ... added_loader = True
2091 >>> try:
2092 ... suite = doctest.DocFileSuite('test_doctest.txt',
2093 ... 'test_doctest2.txt',
2094 ... 'test_doctest4.txt',
2095 ... package='test')
2096 ... suite.run(unittest.TestResult())
2097 ... finally:
2098 ... if added_loader:
2099 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002100 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002101
Edward Loper0273f5b2004-09-18 20:27:04 +00002102 '/' should be used as a path separator. It will be converted
2103 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002104
2105 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2106 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002107 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002108
Edward Loper0273f5b2004-09-18 20:27:04 +00002109 If DocFileSuite is used from an interactive session, then files
2110 are resolved relative to the directory of sys.argv[0]:
2111
Christian Heimes45f9af32007-11-27 21:50:00 +00002112 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002113 >>> save_argv = sys.argv
2114 >>> sys.argv = [test.test_doctest.__file__]
2115 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002116 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002117 >>> sys.argv = save_argv
2118
Edward Loper052d0cd2004-09-19 17:19:33 +00002119 By setting `module_relative=False`, os-specific paths may be
2120 used (including absolute paths and paths relative to the
2121 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002122
2123 >>> # Get the absolute path of the test package.
2124 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2125 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2126
2127 >>> # Use it to find the absolute path of test_doctest.txt.
2128 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2129
Edward Loper052d0cd2004-09-19 17:19:33 +00002130 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002131 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002132 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002133
Edward Loper052d0cd2004-09-19 17:19:33 +00002134 It is an error to specify `package` when `module_relative=False`:
2135
2136 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2137 ... package='test')
2138 Traceback (most recent call last):
2139 ValueError: Package may only be specified for module-relative paths.
2140
Tim Peters19397e52004-08-06 22:02:59 +00002141 You can specify initial global variables:
2142
2143 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2144 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002145 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002146 ... globs={'favorite_color': 'blue'})
2147 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002148 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002149
2150 In this case, we supplied a missing favorite color. You can
2151 provide doctest options:
2152
2153 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2154 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002155 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002156 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2157 ... globs={'favorite_color': 'blue'})
2158 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002159 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002160
2161 And, you can provide setUp and tearDown functions:
2162
Jim Fultonf54bad42004-08-28 14:57:56 +00002163 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002164 ... import test.test_doctest
2165 ... test.test_doctest.sillySetup = True
2166
Jim Fultonf54bad42004-08-28 14:57:56 +00002167 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002168 ... import test.test_doctest
2169 ... del test.test_doctest.sillySetup
2170
2171 Here, we installed a silly variable that the test expects:
2172
2173 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2174 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002175 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002176 ... setUp=setUp, tearDown=tearDown)
2177 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002178 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002179
2180 But the tearDown restores sanity:
2181
2182 >>> import test.test_doctest
2183 >>> test.test_doctest.sillySetup
2184 Traceback (most recent call last):
2185 ...
2186 AttributeError: 'module' object has no attribute 'sillySetup'
2187
Jim Fultonf54bad42004-08-28 14:57:56 +00002188 The setUp and tearDown funtions are passed test objects.
2189 Here, we'll use a setUp function to set the favorite color in
2190 test_doctest.txt:
2191
2192 >>> def setUp(test):
2193 ... test.globs['favorite_color'] = 'blue'
2194
2195 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2196 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002197 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002198
2199 Here, we didn't need to use a tearDown function because we
2200 modified the test globals. The test globals are
2201 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002202
Fred Drake7c404a42004-12-21 23:46:34 +00002203 Tests in a file run using `DocFileSuite` can also access the
2204 `__file__` global, which is set to the name of the file
2205 containing the tests:
2206
2207 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2208 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002209 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002210
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002211 If the tests contain non-ASCII characters, we have to specify which
2212 encoding the file is encoded with. We do so by using the `encoding`
2213 parameter:
2214
2215 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2216 ... 'test_doctest2.txt',
2217 ... 'test_doctest4.txt',
2218 ... encoding='utf-8')
2219 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002220 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002221
Jim Fultonf54bad42004-08-28 14:57:56 +00002222 """
Tim Peters19397e52004-08-06 22:02:59 +00002223
Jim Fulton07a349c2004-08-22 14:10:00 +00002224def test_trailing_space_in_test():
2225 """
Tim Petersa7def722004-08-23 22:13:22 +00002226 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002227
Jim Fulton07a349c2004-08-22 14:10:00 +00002228 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002229 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002230 foo \n
2231 """
Tim Peters19397e52004-08-06 22:02:59 +00002232
Jim Fultonf54bad42004-08-28 14:57:56 +00002233
2234def test_unittest_reportflags():
2235 """Default unittest reporting flags can be set to control reporting
2236
2237 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2238 only the first failure of each test. First, we'll look at the
2239 output without the flag. The file test_doctest.txt file has two
2240 tests. They both fail if blank lines are disabled:
2241
2242 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2243 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2244 >>> import unittest
2245 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002246 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002247 Traceback ...
2248 Failed example:
2249 favorite_color
2250 ...
2251 Failed example:
2252 if 1:
2253 ...
2254
2255 Note that we see both failures displayed.
2256
2257 >>> old = doctest.set_unittest_reportflags(
2258 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2259
2260 Now, when we run the test:
2261
2262 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002263 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002264 Traceback ...
2265 Failed example:
2266 favorite_color
2267 Exception raised:
2268 ...
2269 NameError: name 'favorite_color' is not defined
2270 <BLANKLINE>
2271 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002272
Jim Fultonf54bad42004-08-28 14:57:56 +00002273 We get only the first failure.
2274
2275 If we give any reporting options when we set up the tests,
2276 however:
2277
2278 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2279 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2280
2281 Then the default eporting options are ignored:
2282
2283 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002284 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002285 Traceback ...
2286 Failed example:
2287 favorite_color
2288 ...
2289 Failed example:
2290 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002291 print('a')
2292 print()
2293 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002294 Differences (ndiff with -expected +actual):
2295 a
2296 - <BLANKLINE>
2297 +
2298 b
2299 <BLANKLINE>
2300 <BLANKLINE>
2301
2302
2303 Test runners can restore the formatting flags after they run:
2304
2305 >>> ignored = doctest.set_unittest_reportflags(old)
2306
2307 """
2308
Edward Loper052d0cd2004-09-19 17:19:33 +00002309def test_testfile(): r"""
2310Tests for the `testfile()` function. This function runs all the
2311doctest examples in a given file. In its simple invokation, it is
2312called with the name of a file, which is taken to be relative to the
2313calling module. The return value is (#failures, #tests).
2314
Florent Xicluna59250852010-02-27 14:21:57 +00002315We don't want `-v` in sys.argv for these tests.
2316
2317 >>> save_argv = sys.argv
2318 >>> if '-v' in sys.argv:
2319 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2320
2321
Edward Loper052d0cd2004-09-19 17:19:33 +00002322 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2323 **********************************************************************
2324 File "...", line 6, in test_doctest.txt
2325 Failed example:
2326 favorite_color
2327 Exception raised:
2328 ...
2329 NameError: name 'favorite_color' is not defined
2330 **********************************************************************
2331 1 items had failures:
2332 1 of 2 in test_doctest.txt
2333 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002334 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002335 >>> doctest.master = None # Reset master.
2336
2337(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002338`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002339same name.)
2340
2341Globals may be specified with the `globs` and `extraglobs` parameters:
2342
2343 >>> globs = {'favorite_color': 'blue'}
2344 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002345 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002346 >>> doctest.master = None # Reset master.
2347
2348 >>> extraglobs = {'favorite_color': 'red'}
2349 >>> doctest.testfile('test_doctest.txt', globs=globs,
2350 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2351 **********************************************************************
2352 File "...", line 6, in test_doctest.txt
2353 Failed example:
2354 favorite_color
2355 Expected:
2356 'blue'
2357 Got:
2358 'red'
2359 **********************************************************************
2360 1 items had failures:
2361 1 of 2 in test_doctest.txt
2362 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002363 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002364 >>> doctest.master = None # Reset master.
2365
2366The file may be made relative to a given module or package, using the
2367optional `module_relative` parameter:
2368
2369 >>> doctest.testfile('test_doctest.txt', globs=globs,
2370 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002371 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002372 >>> doctest.master = None # Reset master.
2373
Ezio Melotti13925002011-03-16 11:05:33 +02002374Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002375
2376 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2377 Trying:
2378 favorite_color
2379 Expecting:
2380 'blue'
2381 ok
2382 Trying:
2383 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002384 print('a')
2385 print()
2386 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002387 Expecting:
2388 a
2389 <BLANKLINE>
2390 b
2391 ok
2392 1 items passed all tests:
2393 2 tests in test_doctest.txt
2394 2 tests in 1 items.
2395 2 passed and 0 failed.
2396 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002397 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002398 >>> doctest.master = None # Reset master.
2399
2400The name of the test may be specified with the optional `name`
2401parameter:
2402
2403 >>> doctest.testfile('test_doctest.txt', name='newname')
2404 ... # doctest: +ELLIPSIS
2405 **********************************************************************
2406 File "...", line 6, in newname
2407 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002408 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002409 >>> doctest.master = None # Reset master.
2410
Ezio Melotti13925002011-03-16 11:05:33 +02002411The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002412parameter:
2413
2414 >>> doctest.testfile('test_doctest.txt', report=False)
2415 ... # doctest: +ELLIPSIS
2416 **********************************************************************
2417 File "...", line 6, in test_doctest.txt
2418 Failed example:
2419 favorite_color
2420 Exception raised:
2421 ...
2422 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002423 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002424 >>> doctest.master = None # Reset master.
2425
2426The optional keyword argument `raise_on_error` can be used to raise an
2427exception on the first error (which may be useful for postmortem
2428debugging):
2429
2430 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2431 ... # doctest: +ELLIPSIS
2432 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002433 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002434 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002435
2436If the tests contain non-ASCII characters, the tests might fail, since
2437it's unknown which encoding is used. The encoding can be specified
2438using the optional keyword argument `encoding`:
2439
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002440 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002441 **********************************************************************
2442 File "...", line 7, in test_doctest4.txt
2443 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002444 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002445 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002446 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002447 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002448 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002449 **********************************************************************
2450 ...
2451 **********************************************************************
2452 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002453 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002454 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002455 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002456 >>> doctest.master = None # Reset master.
2457
2458 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002459 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002460 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002461
2462Test the verbose output:
2463
2464 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2465 Trying:
2466 'föö'
2467 Expecting:
2468 'f\xf6\xf6'
2469 ok
2470 Trying:
2471 'bąr'
2472 Expecting:
2473 'b\u0105r'
2474 ok
2475 1 items passed all tests:
2476 2 tests in test_doctest4.txt
2477 2 tests in 1 items.
2478 2 passed and 0 failed.
2479 Test passed.
2480 TestResults(failed=0, attempted=2)
2481 >>> doctest.master = None # Reset master.
2482 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002483"""
2484
R. David Murray58641de2009-06-12 15:33:19 +00002485def test_testmod(): r"""
2486Tests for the testmod function. More might be useful, but for now we're just
2487testing the case raised by Issue 6195, where trying to doctest a C module would
2488fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2489out of the binary module.
2490
2491 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002492 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002493 TestResults(failed=0, attempted=0)
2494"""
2495
Victor Stinner9d396392010-10-16 21:54:59 +00002496try:
2497 os.fsencode("foo-bär@baz.py")
2498except UnicodeEncodeError:
2499 # Skip the test: the filesystem encoding is unable to encode the filename
2500 pass
2501else:
2502 def test_unicode(): """
2503Check doctest with a non-ascii filename:
2504
2505 >>> doc = '''
2506 ... >>> raise Exception('clé')
2507 ... '''
2508 ...
2509 >>> parser = doctest.DocTestParser()
2510 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2511 >>> test
2512 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2513 >>> runner = doctest.DocTestRunner(verbose=False)
2514 >>> runner.run(test) # doctest: +ELLIPSIS
2515 **********************************************************************
2516 File "foo-bär@baz.py", line 2, in foo-bär@baz
2517 Failed example:
2518 raise Exception('clé')
2519 Exception raised:
2520 Traceback (most recent call last):
2521 File ...
2522 compileflags, 1), test.globs)
2523 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2524 raise Exception('clé')
2525 Exception: clé
2526 TestResults(failed=1, attempted=1)
2527 """
2528
Tim Peters8485b562004-08-04 18:46:34 +00002529######################################################################
2530## Main
2531######################################################################
2532
2533def test_main():
2534 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002535 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002536 # Check the doctest cases defined here:
2537 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002538 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002539
Victor Stinner45df8202010-04-28 22:31:17 +00002540import sys, re, io
2541
Tim Peters8485b562004-08-04 18:46:34 +00002542def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002543 trace = support.import_module('trace')
Tim Peters8485b562004-08-04 18:46:34 +00002544 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2545 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002546 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002547 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002548 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002549 r.write_results(show_missing=True, summary=True,
2550 coverdir=coverdir)
2551
2552if __name__ == '__main__':
2553 if '-c' in sys.argv:
2554 test_coverage('/tmp/doctest.cover')
2555 else:
2556 test_main()