blob: ff012388bd7d49b2f202df3359a02b61968d58dc [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
7
Nick Coghlanf088e5e2008-12-14 11:50:48 +00008# NOTE: There are some additional tests relating to interaction with
9# zipimport in the test_zipimport_support test module.
10
Tim Peters8485b562004-08-04 18:46:34 +000011######################################################################
12## Sample Objects (used by test cases)
13######################################################################
14
15def sample_func(v):
16 """
Tim Peters19397e52004-08-06 22:02:59 +000017 Blah blah
18
Guido van Rossum7131f842007-02-09 20:13:25 +000019 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000020 44
Tim Peters19397e52004-08-06 22:02:59 +000021
22 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000023 """
24 return v+v
25
26class SampleClass:
27 """
Guido van Rossum7131f842007-02-09 20:13:25 +000028 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000029 1
Edward Loper4ae900f2004-09-21 03:20:34 +000030
31 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
32 >>>
33 ...
34
35 Multiline example:
36 >>> sc = SampleClass(3)
37 >>> for i in range(10):
38 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000039 ... print(' ', sc.get(), sep='', end='')
40 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000041 """
42 def __init__(self, val):
43 """
Guido van Rossum7131f842007-02-09 20:13:25 +000044 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000045 12
46 """
47 self.val = val
48
49 def double(self):
50 """
Guido van Rossum7131f842007-02-09 20:13:25 +000051 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000052 24
53 """
54 return SampleClass(self.val + self.val)
55
56 def get(self):
57 """
Guido van Rossum7131f842007-02-09 20:13:25 +000058 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000059 -5
60 """
61 return self.val
62
63 def a_staticmethod(v):
64 """
Guido van Rossum7131f842007-02-09 20:13:25 +000065 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000066 11
67 """
68 return v+1
69 a_staticmethod = staticmethod(a_staticmethod)
70
71 def a_classmethod(cls, v):
72 """
Guido van Rossum7131f842007-02-09 20:13:25 +000073 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000074 12
Guido van Rossum7131f842007-02-09 20:13:25 +000075 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000076 12
77 """
78 return v+2
79 a_classmethod = classmethod(a_classmethod)
80
81 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000082 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000083 22
84 """)
85
86 class NestedClass:
87 """
88 >>> x = SampleClass.NestedClass(5)
89 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000090 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000091 25
92 """
93 def __init__(self, val=0):
94 """
Guido van Rossum7131f842007-02-09 20:13:25 +000095 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +000096 0
97 """
98 self.val = val
99 def square(self):
100 return SampleClass.NestedClass(self.val*self.val)
101 def get(self):
102 return self.val
103
104class SampleNewStyleClass(object):
105 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000106 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000107 1
108 2
109 3
110 """
111 def __init__(self, val):
112 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000113 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000114 12
115 """
116 self.val = val
117
118 def double(self):
119 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000120 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000121 24
122 """
123 return SampleNewStyleClass(self.val + self.val)
124
125 def get(self):
126 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000127 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000128 -5
129 """
130 return self.val
131
132######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000133## Fake stdin (for testing interactive debugging)
134######################################################################
135
136class _FakeInput:
137 """
138 A fake input stream for pdb's interactive debugger. Whenever a
139 line is read, print it (to simulate the user typing it), and then
140 return it. The set of lines to return is specified in the
141 constructor; they should not have trailing newlines.
142 """
143 def __init__(self, lines):
144 self.lines = lines
145
146 def readline(self):
147 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000148 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000149 return line+'\n'
150
151######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000152## Test Cases
153######################################################################
154
155def test_Example(): r"""
156Unit tests for the `Example` class.
157
Edward Lopera6b68322004-08-26 00:05:43 +0000158Example is a simple container class that holds:
159 - `source`: A source string.
160 - `want`: An expected output string.
161 - `exc_msg`: An expected exception message string (or None if no
162 exception is expected).
163 - `lineno`: A line number (within the docstring).
164 - `indent`: The example's indentation in the input string.
165 - `options`: An option dictionary, mapping option flags to True or
166 False.
Tim Peters8485b562004-08-04 18:46:34 +0000167
Edward Lopera6b68322004-08-26 00:05:43 +0000168These attributes are set by the constructor. `source` and `want` are
169required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000170
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000171 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000172 >>> (example.source, example.want, example.exc_msg,
173 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000174 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000175
176The first three attributes (`source`, `want`, and `exc_msg`) may be
177specified positionally; the remaining arguments should be specified as
178keyword arguments:
179
180 >>> exc_msg = 'IndexError: pop from an empty list'
181 >>> example = doctest.Example('[].pop()', '', exc_msg,
182 ... lineno=5, indent=4,
183 ... options={doctest.ELLIPSIS: True})
184 >>> (example.source, example.want, example.exc_msg,
185 ... example.lineno, example.indent, example.options)
186 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
187
188The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000189
Tim Petersbb431472004-08-09 03:51:46 +0000190 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000191 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000192 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000193 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000194
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000195 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000196 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000197 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000198
Tim Petersbb431472004-08-09 03:51:46 +0000199 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000200 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000201 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000202 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000203
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000204 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000205 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000206 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000207
Edward Lopera6b68322004-08-26 00:05:43 +0000208 Empty source string (which should never appear in real examples)
209 >>> e = doctest.Example('', '')
210 >>> e.source, e.want
211 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000212
Edward Lopera6b68322004-08-26 00:05:43 +0000213The constructor normalizes the `want` string to end in a newline,
214unless it's the empty string:
215
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000216 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000217 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000218 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000219
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000220 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000221 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000222 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000223
Edward Lopera6b68322004-08-26 00:05:43 +0000224 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000225 >>> e.source, e.want
226 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000227
228The constructor normalizes the `exc_msg` string to end in a newline,
229unless it's `None`:
230
231 Message spans one line
232 >>> exc_msg = 'IndexError: pop from an empty list'
233 >>> e = doctest.Example('[].pop()', '', exc_msg)
234 >>> e.exc_msg
235 'IndexError: pop from an empty list\n'
236
237 >>> exc_msg = 'IndexError: pop from an empty list\n'
238 >>> e = doctest.Example('[].pop()', '', exc_msg)
239 >>> e.exc_msg
240 'IndexError: pop from an empty list\n'
241
242 Message spans multiple lines
243 >>> exc_msg = 'ValueError: 1\n 2'
244 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
245 >>> e.exc_msg
246 'ValueError: 1\n 2\n'
247
248 >>> exc_msg = 'ValueError: 1\n 2\n'
249 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
250 >>> e.exc_msg
251 'ValueError: 1\n 2\n'
252
253 Empty (but non-None) exception message (which should never appear
254 in real examples)
255 >>> exc_msg = ''
256 >>> e = doctest.Example('raise X()', '', exc_msg)
257 >>> e.exc_msg
258 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000259"""
260
261def test_DocTest(): r"""
262Unit tests for the `DocTest` class.
263
264DocTest is a collection of examples, extracted from a docstring, along
265with information about where the docstring comes from (a name,
266filename, and line number). The docstring is parsed by the `DocTest`
267constructor:
268
269 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000270 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000271 ... 12
272 ...
273 ... Non-example text.
274 ...
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000275 ... >>> print('another\example')
Tim Peters8485b562004-08-04 18:46:34 +0000276 ... another
277 ... example
278 ... '''
279 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000280 >>> parser = doctest.DocTestParser()
281 >>> test = parser.get_doctest(docstring, globs, 'some_test',
282 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000283 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000284 <DocTest some_test from some_file:20 (2 examples)>
285 >>> len(test.examples)
286 2
287 >>> e1, e2 = test.examples
288 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000289 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000290 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000291 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000292
293Source information (name, filename, and line number) is available as
294attributes on the doctest object:
295
296 >>> (test.name, test.filename, test.lineno)
297 ('some_test', 'some_file', 20)
298
299The line number of an example within its containing file is found by
300adding the line number of the example and the line number of its
301containing test:
302
303 >>> test.lineno + e1.lineno
304 21
305 >>> test.lineno + e2.lineno
306 26
307
308If the docstring contains inconsistant leading whitespace in the
309expected output of an example, then `DocTest` will raise a ValueError:
310
311 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000312 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000313 ... bad
314 ... indentation
315 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000316 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000317 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000318 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000319
320If the docstring contains inconsistent leading whitespace on
321continuation lines, then `DocTest` will raise a ValueError:
322
323 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000324 ... >>> print(('bad indentation',
325 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000326 ... ('bad', 'indentation')
327 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000328 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000329 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000330 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000331
332If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
333will raise a ValueError:
334
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000335 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000336 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000337 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000338 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000339
340If there's no blank space after a PS2 prompt ('...'), then `DocTest`
341will raise a ValueError:
342
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000343 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000344 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000345 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000346 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000347
Tim Peters8485b562004-08-04 18:46:34 +0000348"""
349
Tim Peters8485b562004-08-04 18:46:34 +0000350def test_DocTestFinder(): r"""
351Unit tests for the `DocTestFinder` class.
352
353DocTestFinder is used to extract DocTests from an object's docstring
354and the docstrings of its contained objects. It can be used with
355modules, functions, classes, methods, staticmethods, classmethods, and
356properties.
357
358Finding Tests in Functions
359~~~~~~~~~~~~~~~~~~~~~~~~~~
360For a function whose docstring contains examples, DocTestFinder.find()
361will return a single test (for that function's docstring):
362
Tim Peters8485b562004-08-04 18:46:34 +0000363 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000364
365We'll simulate a __file__ attr that ends in pyc:
366
367 >>> import test.test_doctest
368 >>> old = test.test_doctest.__file__
369 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
370
Tim Peters8485b562004-08-04 18:46:34 +0000371 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000372
Guido van Rossum7131f842007-02-09 20:13:25 +0000373 >>> print(tests) # doctest: +ELLIPSIS
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000374 [<DocTest sample_func from ...:16 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000375
Tim Peters4de7c5c2004-08-23 22:38:05 +0000376The exact name depends on how test_doctest was invoked, so allow for
377leading path components.
378
379 >>> tests[0].filename # doctest: +ELLIPSIS
380 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000381
382 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000383
Jim Fulton07a349c2004-08-22 14:10:00 +0000384
Tim Peters8485b562004-08-04 18:46:34 +0000385 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000386 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000387 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000388
Edward Loper32ddbf72004-09-13 05:47:24 +0000389By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000390
391 >>> def no_docstring(v):
392 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000393 >>> finder.find(no_docstring)
394 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000395
396However, the optional argument `exclude_empty` to the DocTestFinder
397constructor can be used to exclude tests for objects with empty
398docstrings:
399
400 >>> def no_docstring(v):
401 ... pass
402 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
403 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000404 []
405
406If the function has a docstring with no examples, then a test with no
407examples is returned. (This lets `DocTestRunner` collect statistics
408about which functions have no tests -- but is that useful? And should
409an empty test also be created when there's no docstring?)
410
411 >>> def no_examples(v):
412 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000413 >>> finder.find(no_examples) # doctest: +ELLIPSIS
414 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000415
416Finding Tests in Classes
417~~~~~~~~~~~~~~~~~~~~~~~~
418For a class, DocTestFinder will create a test for the class's
419docstring, and will recursively explore its contents, including
420methods, classmethods, staticmethods, properties, and nested classes.
421
422 >>> finder = doctest.DocTestFinder()
423 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000424 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000425 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000426 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000427 3 SampleClass.NestedClass
428 1 SampleClass.NestedClass.__init__
429 1 SampleClass.__init__
430 2 SampleClass.a_classmethod
431 1 SampleClass.a_property
432 1 SampleClass.a_staticmethod
433 1 SampleClass.double
434 1 SampleClass.get
435
436New-style classes are also supported:
437
438 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000439 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000440 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000441 1 SampleNewStyleClass
442 1 SampleNewStyleClass.__init__
443 1 SampleNewStyleClass.double
444 1 SampleNewStyleClass.get
445
446Finding Tests in Modules
447~~~~~~~~~~~~~~~~~~~~~~~~
448For a module, DocTestFinder will create a test for the class's
449docstring, and will recursively explore its contents, including
450functions, classes, and the `__test__` dictionary, if it exists:
451
452 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000453 >>> import types
454 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000455 >>> def triple(val):
456 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000457 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000458 ... 33
459 ... '''
460 ... return val*3
461 >>> m.__dict__.update({
462 ... 'sample_func': sample_func,
463 ... 'SampleClass': SampleClass,
464 ... '__doc__': '''
465 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000466 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000467 ... module
468 ... ''',
469 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000470 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000471 ... 'c': triple}})
472
473 >>> finder = doctest.DocTestFinder()
474 >>> # Use module=test.test_doctest, to prevent doctest from
475 >>> # ignoring the objects since they weren't defined in m.
476 >>> import test.test_doctest
477 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000478 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000479 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000480 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000481 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000482 3 some_module.SampleClass.NestedClass
483 1 some_module.SampleClass.NestedClass.__init__
484 1 some_module.SampleClass.__init__
485 2 some_module.SampleClass.a_classmethod
486 1 some_module.SampleClass.a_property
487 1 some_module.SampleClass.a_staticmethod
488 1 some_module.SampleClass.double
489 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000490 1 some_module.__test__.c
491 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000492 1 some_module.sample_func
493
494Duplicate Removal
495~~~~~~~~~~~~~~~~~
496If a single object is listed twice (under different names), then tests
497will only be generated for it once:
498
Tim Petersf3f57472004-08-08 06:11:48 +0000499 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000500 >>> assert doctest_aliases.TwoNames.f
501 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000502 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000503 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000504 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000505 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000506 test.doctest_aliases.TwoNames
507
508 TwoNames.f and TwoNames.g are bound to the same object.
509 We can't guess which will be found in doctest's traversal of
510 TwoNames.__dict__ first, so we have to allow for either.
511
512 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000513 True
514
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000515Empty Tests
516~~~~~~~~~~~
517By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000518
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000519 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000520 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000521 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000522 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000523 3 SampleClass.NestedClass
524 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000525 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000526 2 SampleClass.a_classmethod
527 1 SampleClass.a_property
528 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000529 1 SampleClass.double
530 1 SampleClass.get
531
532By default, that excluded objects with no doctests. exclude_empty=False
533tells it to include (empty) tests for objects with no doctests. This feature
534is really to support backward compatibility in what doctest.master.summarize()
535displays.
536
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000537 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000538 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000539 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000540 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000541 3 SampleClass.NestedClass
542 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000543 0 SampleClass.NestedClass.get
544 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000545 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000546 2 SampleClass.a_classmethod
547 1 SampleClass.a_property
548 1 SampleClass.a_staticmethod
549 1 SampleClass.double
550 1 SampleClass.get
551
Tim Peters8485b562004-08-04 18:46:34 +0000552Turning off Recursion
553~~~~~~~~~~~~~~~~~~~~~
554DocTestFinder can be told not to look for tests in contained objects
555using the `recurse` flag:
556
557 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000558 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000559 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000560 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000561
562Line numbers
563~~~~~~~~~~~~
564DocTestFinder finds the line number of each example:
565
566 >>> def f(x):
567 ... '''
568 ... >>> x = 12
569 ...
570 ... some text
571 ...
572 ... >>> # examples are not created for comments & bare prompts.
573 ... >>>
574 ... ...
575 ...
576 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000577 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000578 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000579 ... >>> x//2
580 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000581 ... '''
582 >>> test = doctest.DocTestFinder().find(f)[0]
583 >>> [e.lineno for e in test.examples]
584 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000585"""
586
Edward Loper00f8da72004-08-26 18:05:07 +0000587def test_DocTestParser(): r"""
588Unit tests for the `DocTestParser` class.
589
590DocTestParser is used to parse docstrings containing doctest examples.
591
592The `parse` method divides a docstring into examples and intervening
593text:
594
595 >>> s = '''
596 ... >>> x, y = 2, 3 # no output expected
597 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000598 ... ... print(x)
599 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000600 ... 2
601 ... 3
602 ...
603 ... Some text.
604 ... >>> x+y
605 ... 5
606 ... '''
607 >>> parser = doctest.DocTestParser()
608 >>> for piece in parser.parse(s):
609 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000610 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000611 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000612 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000613 Text: '\n'
614 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
615 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000616 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000617 Text: '\nSome text.\n'
618 Example: ('x+y\n', '5\n', 9)
619 Text: ''
620
621The `get_examples` method returns just the examples:
622
623 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000624 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000625 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000626 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000627 ('x+y\n', '5\n', 9)
628
629The `get_doctest` method creates a Test from the examples, along with the
630given arguments:
631
632 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
633 >>> (test.name, test.filename, test.lineno)
634 ('name', 'filename', 5)
635 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000636 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000637 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000638 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000639 ('x+y\n', '5\n', 9)
640"""
641
Tim Peters8485b562004-08-04 18:46:34 +0000642class test_DocTestRunner:
643 def basics(): r"""
644Unit tests for the `DocTestRunner` class.
645
646DocTestRunner is used to run DocTest test cases, and to accumulate
647statistics. Here's a simple DocTest case we can use:
648
649 >>> def f(x):
650 ... '''
651 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000652 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000653 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000654 ... >>> x//2
655 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000656 ... '''
657 >>> test = doctest.DocTestFinder().find(f)[0]
658
659The main DocTestRunner interface is the `run` method, which runs a
660given DocTest case in a given namespace (globs). It returns a tuple
661`(f,t)`, where `f` is the number of failed tests and `t` is the number
662of tried tests.
663
664 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000665 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000666
667If any example produces incorrect output, then the test runner reports
668the failure and proceeds to the next example:
669
670 >>> def f(x):
671 ... '''
672 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000673 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000674 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000675 ... >>> x//2
676 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000677 ... '''
678 >>> test = doctest.DocTestFinder().find(f)[0]
679 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000680 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000681 Trying:
682 x = 12
683 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000684 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000685 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000686 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000687 Expecting:
688 14
Tim Peters8485b562004-08-04 18:46:34 +0000689 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000690 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000691 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000692 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000693 Expected:
694 14
695 Got:
696 12
Edward Loperaacf0832004-08-26 01:19:50 +0000697 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000698 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000699 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000700 6
Tim Peters8485b562004-08-04 18:46:34 +0000701 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000702 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000703"""
704 def verbose_flag(): r"""
705The `verbose` flag makes the test runner generate more detailed
706output:
707
708 >>> def f(x):
709 ... '''
710 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000711 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000712 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000713 ... >>> x//2
714 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000715 ... '''
716 >>> test = doctest.DocTestFinder().find(f)[0]
717
718 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000719 Trying:
720 x = 12
721 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000722 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000723 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000724 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000725 Expecting:
726 12
Tim Peters8485b562004-08-04 18:46:34 +0000727 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000728 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000729 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000730 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000731 6
Tim Peters8485b562004-08-04 18:46:34 +0000732 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000733 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000734
735If the `verbose` flag is unspecified, then the output will be verbose
736iff `-v` appears in sys.argv:
737
738 >>> # Save the real sys.argv list.
739 >>> old_argv = sys.argv
740
741 >>> # If -v does not appear in sys.argv, then output isn't verbose.
742 >>> sys.argv = ['test']
743 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000744 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000745
746 >>> # If -v does appear in sys.argv, then output is verbose.
747 >>> sys.argv = ['test', '-v']
748 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000749 Trying:
750 x = 12
751 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000752 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000753 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000754 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000755 Expecting:
756 12
Tim Peters8485b562004-08-04 18:46:34 +0000757 ok
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=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000764
765 >>> # Restore sys.argv
766 >>> sys.argv = old_argv
767
768In the remaining examples, the test runner's verbosity will be
769explicitly set, to ensure that the test behavior is consistent.
770 """
771 def exceptions(): r"""
772Tests of `DocTestRunner`'s exception handling.
773
774An expected exception is specified with a traceback message. The
775lines between the first line and the type/value may be omitted or
776replaced with any other string:
777
778 >>> def f(x):
779 ... '''
780 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000781 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000782 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000783 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000784 ... '''
785 >>> test = doctest.DocTestFinder().find(f)[0]
786 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000787 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000788
Edward Loper19b19582004-08-25 23:07:03 +0000789An example may not generate output before it raises an exception; if
790it does, then the traceback message will not be recognized as
791signaling an expected exception, so the example will be reported as an
792unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000793
794 >>> def f(x):
795 ... '''
796 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000797 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000798 ... pre-exception output
799 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000800 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000801 ... '''
802 >>> test = doctest.DocTestFinder().find(f)[0]
803 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000804 ... # doctest: +ELLIPSIS
805 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000806 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000807 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000808 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000809 Exception raised:
810 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000811 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000812 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000813
814Exception messages may contain newlines:
815
816 >>> def f(x):
817 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000818 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000819 ... Traceback (most recent call last):
820 ... ValueError: multi
821 ... line
822 ... message
823 ... '''
824 >>> test = doctest.DocTestFinder().find(f)[0]
825 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000826 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000827
828If an exception is expected, but an exception with the wrong type or
829message is raised, then it is reported as a failure:
830
831 >>> def f(x):
832 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000833 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000834 ... Traceback (most recent call last):
835 ... ValueError: wrong message
836 ... '''
837 >>> test = doctest.DocTestFinder().find(f)[0]
838 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000839 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000840 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000841 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000842 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000843 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000844 Expected:
845 Traceback (most recent call last):
846 ValueError: wrong message
847 Got:
848 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000849 ...
Tim Peters8485b562004-08-04 18:46:34 +0000850 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000851 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000852
Tim Peters1fbf9c52004-09-04 17:21:02 +0000853However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
854detail:
855
856 >>> def f(x):
857 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000858 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000859 ... Traceback (most recent call last):
860 ... ValueError: wrong message
861 ... '''
862 >>> test = doctest.DocTestFinder().find(f)[0]
863 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000864 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000865
866But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
867
868 >>> def f(x):
869 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000870 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000871 ... Traceback (most recent call last):
872 ... TypeError: wrong type
873 ... '''
874 >>> test = doctest.DocTestFinder().find(f)[0]
875 >>> doctest.DocTestRunner(verbose=False).run(test)
876 ... # doctest: +ELLIPSIS
877 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000878 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000879 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000880 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000881 Expected:
882 Traceback (most recent call last):
883 TypeError: wrong type
884 Got:
885 Traceback (most recent call last):
886 ...
887 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000888 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000889
Tim Peters8485b562004-08-04 18:46:34 +0000890If an exception is raised but not expected, then it is reported as an
891unexpected exception:
892
Tim Peters8485b562004-08-04 18:46:34 +0000893 >>> def f(x):
894 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000895 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000896 ... 0
897 ... '''
898 >>> test = doctest.DocTestFinder().find(f)[0]
899 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +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:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000904 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000905 Exception raised:
906 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000907 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000908 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000909 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000910"""
911 def optionflags(): r"""
912Tests of `DocTestRunner`'s option flag handling.
913
914Several option flags can be used to customize the behavior of the test
915runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +0000916to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +0000917together).
918
919The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
920and 1/0:
921
922 >>> def f(x):
923 ... '>>> True\n1\n'
924
925 >>> # Without the flag:
926 >>> test = doctest.DocTestFinder().find(f)[0]
927 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000928 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000929
930 >>> # With the flag:
931 >>> test = doctest.DocTestFinder().find(f)[0]
932 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
933 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000934 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000935 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000936 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000937 Failed example:
938 True
939 Expected:
940 1
941 Got:
942 True
Christian Heimes25bb7832008-01-11 16:17:00 +0000943 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000944
945The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
946and the '<BLANKLINE>' marker:
947
948 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000949 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +0000950
951 >>> # Without the flag:
952 >>> test = doctest.DocTestFinder().find(f)[0]
953 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000954 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000955
956 >>> # With the flag:
957 >>> test = doctest.DocTestFinder().find(f)[0]
958 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
959 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000960 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000961 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000962 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000963 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000964 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +0000965 Expected:
966 a
967 <BLANKLINE>
968 b
969 Got:
970 a
971 <BLANKLINE>
972 b
Christian Heimes25bb7832008-01-11 16:17:00 +0000973 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000974
975The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
976treated as equal:
977
978 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000979 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +0000980
981 >>> # Without the flag:
982 >>> test = doctest.DocTestFinder().find(f)[0]
983 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000984 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000985 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000986 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000987 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000988 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +0000989 Expected:
990 1 2
991 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000992 Got:
993 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +0000994 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000995
996 >>> # With the flag:
997 >>> test = doctest.DocTestFinder().find(f)[0]
998 >>> flags = doctest.NORMALIZE_WHITESPACE
999 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001000 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001001
Tim Peters026f8dc2004-08-19 16:38:58 +00001002 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001003 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001004 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1005 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1006
Tim Peters8485b562004-08-04 18:46:34 +00001007The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1008output to match any substring in the actual output:
1009
1010 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001011 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001012
1013 >>> # Without the flag:
1014 >>> test = doctest.DocTestFinder().find(f)[0]
1015 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001016 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001017 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001018 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001019 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001020 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001021 Expected:
1022 [0, 1, 2, ..., 14]
1023 Got:
1024 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001025 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001026
1027 >>> # With the flag:
1028 >>> test = doctest.DocTestFinder().find(f)[0]
1029 >>> flags = doctest.ELLIPSIS
1030 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001031 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001032
Tim Peterse594bee2004-08-22 01:47:51 +00001033 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001034
Guido van Rossume0192e52007-02-09 23:39:59 +00001035 >>> if 1:
1036 ... for i in range(100):
1037 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1038 ... print('!')
1039 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001040
Tim Peters026f8dc2004-08-19 16:38:58 +00001041 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001042
Guido van Rossume0192e52007-02-09 23:39:59 +00001043 >>> if 1: #doctest: +ELLIPSIS
1044 ... for i in range(20):
1045 ... print(i, end=' ')
1046 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001047 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001048
Tim Peters026f8dc2004-08-19 16:38:58 +00001049 Examples from the docs:
1050
Guido van Rossum805365e2007-05-07 22:24:25 +00001051 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001052 [0, 1, ..., 18, 19]
1053
Guido van Rossum805365e2007-05-07 22:24:25 +00001054 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001055 ... # doctest: +NORMALIZE_WHITESPACE
1056 [0, 1, ..., 18, 19]
1057
Thomas Wouters477c8d52006-05-27 19:21:47 +00001058The SKIP flag causes an example to be skipped entirely. I.e., the
1059example is not run. It can be useful in contexts where doctest
1060examples serve as both documentation and test cases, and an example
1061should be included for documentation purposes, but should not be
1062checked (e.g., because its output is random, or depends on resources
1063which would be unavailable.) The SKIP flag can also be used for
1064'commenting out' broken examples.
1065
1066 >>> import unavailable_resource # doctest: +SKIP
1067 >>> unavailable_resource.do_something() # doctest: +SKIP
1068 >>> unavailable_resource.blow_up() # doctest: +SKIP
1069 Traceback (most recent call last):
1070 ...
1071 UncheckedBlowUpError: Nobody checks me.
1072
1073 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001074 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001075 0.721216923889
1076
Edward Loper71f55af2004-08-26 01:41:51 +00001077The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001078and actual outputs to be displayed using a unified diff:
1079
1080 >>> def f(x):
1081 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001082 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001083 ... a
1084 ... B
1085 ... c
1086 ... d
1087 ... f
1088 ... g
1089 ... h
1090 ... '''
1091
1092 >>> # Without the flag:
1093 >>> test = doctest.DocTestFinder().find(f)[0]
1094 >>> doctest.DocTestRunner(verbose=False).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 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001098 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001099 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001100 Expected:
1101 a
1102 B
1103 c
1104 d
1105 f
1106 g
1107 h
1108 Got:
1109 a
1110 b
1111 c
1112 d
1113 e
1114 f
1115 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001116 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001117
1118 >>> # With the flag:
1119 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001120 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001121 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001122 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001123 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001124 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001125 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001126 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001127 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001128 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001129 a
1130 -B
1131 +b
1132 c
1133 d
1134 +e
1135 f
1136 g
1137 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001138 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001139
Edward Loper71f55af2004-08-26 01:41:51 +00001140The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001141and actual outputs to be displayed using a context diff:
1142
Edward Loper71f55af2004-08-26 01:41:51 +00001143 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001144 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001145 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001146 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001147 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001148 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001149 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001150 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001151 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001152 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001153 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001154 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001155 a
1156 ! B
1157 c
1158 d
1159 f
1160 g
1161 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001162 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001163 a
1164 ! b
1165 c
1166 d
1167 + e
1168 f
1169 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001170 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001171
1172
Edward Loper71f55af2004-08-26 01:41:51 +00001173The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001174used by the popular ndiff.py utility. This does intraline difference
1175marking, as well as interline differences.
1176
1177 >>> def f(x):
1178 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001179 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001180 ... a b c d e f g h i j k 1 m
1181 ... '''
1182 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001183 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001184 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001185 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001186 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001187 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001188 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001189 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001190 Differences (ndiff with -expected +actual):
1191 - a b c d e f g h i j k 1 m
1192 ? ^
1193 + a b c d e f g h i j k l m
1194 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001195 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001196
1197The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1198failing example:
1199
1200 >>> def f(x):
1201 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001202 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001203 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001204 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001205 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001206 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001207 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001208 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001209 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001210 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001211 ... 500
1212 ... '''
1213 >>> test = doctest.DocTestFinder().find(f)[0]
1214 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1215 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001216 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001217 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001218 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001219 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001220 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001221 Expected:
1222 200
1223 Got:
1224 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001225 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001226
1227However, output from `report_start` is not supressed:
1228
1229 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001230 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001231 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001232 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001233 Expecting:
1234 1
1235 ok
1236 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001237 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001238 Expecting:
1239 200
1240 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001241 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001242 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001243 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001244 Expected:
1245 200
1246 Got:
1247 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001248 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001249
1250For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1251count as failures:
1252
1253 >>> def f(x):
1254 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001255 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001256 ... 1
1257 ... >>> raise ValueError(2) # first failure
1258 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001259 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001260 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001261 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001262 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001263 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001264 ... 500
1265 ... '''
1266 >>> test = doctest.DocTestFinder().find(f)[0]
1267 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1268 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1269 ... # doctest: +ELLIPSIS
1270 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001271 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001272 Failed example:
1273 raise ValueError(2) # first failure
1274 Exception raised:
1275 ...
1276 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001277 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001278
Thomas Wouters477c8d52006-05-27 19:21:47 +00001279New option flags can also be registered, via register_optionflag(). Here
1280we reach into doctest's internals a bit.
1281
1282 >>> unlikely = "UNLIKELY_OPTION_NAME"
1283 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1284 False
1285 >>> new_flag_value = doctest.register_optionflag(unlikely)
1286 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1287 True
1288
1289Before 2.4.4/2.5, registering a name more than once erroneously created
1290more than one flag value. Here we verify that's fixed:
1291
1292 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1293 >>> redundant_flag_value == new_flag_value
1294 True
1295
1296Clean up.
1297 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1298
Tim Petersc6cbab02004-08-22 19:43:28 +00001299 """
1300
Tim Peters8485b562004-08-04 18:46:34 +00001301 def option_directives(): r"""
1302Tests of `DocTestRunner`'s option directive mechanism.
1303
Edward Loper74bca7a2004-08-12 02:27:44 +00001304Option directives can be used to turn option flags on or off for a
1305single example. To turn an option on for an example, follow that
1306example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001307
1308 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001309 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001310 ... [0, 1, ..., 9]
1311 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001312 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001313 ... [0, 1, ..., 9]
1314 ... '''
1315 >>> test = doctest.DocTestFinder().find(f)[0]
1316 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001317 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001318 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001319 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001320 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001321 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001322 Expected:
1323 [0, 1, ..., 9]
1324 Got:
1325 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001326 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001327
1328To turn an option off for an example, follow that example with a
1329comment of the form ``# doctest: -OPTION``:
1330
1331 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001332 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001333 ... [0, 1, ..., 9]
1334 ...
1335 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001336 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001337 ... [0, 1, ..., 9]
1338 ... '''
1339 >>> test = doctest.DocTestFinder().find(f)[0]
1340 >>> doctest.DocTestRunner(verbose=False,
1341 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001342 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001343 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001344 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001345 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001346 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001347 Expected:
1348 [0, 1, ..., 9]
1349 Got:
1350 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001351 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001352
1353Option directives affect only the example that they appear with; they
1354do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001355
Edward Loper74bca7a2004-08-12 02:27:44 +00001356 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001357 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001358 ... [0, 1, ..., 9]
1359 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001360 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001361 ... [0, 1, ..., 9]
1362 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001363 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001364 ... [0, 1, ..., 9]
1365 ... '''
1366 >>> test = doctest.DocTestFinder().find(f)[0]
1367 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001368 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001369 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001370 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001371 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001372 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001373 Expected:
1374 [0, 1, ..., 9]
1375 Got:
1376 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001377 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001378 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001379 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001380 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001381 Expected:
1382 [0, 1, ..., 9]
1383 Got:
1384 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001385 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001386
Edward Loper74bca7a2004-08-12 02:27:44 +00001387Multiple options may be modified by a single option directive. They
1388may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001389
1390 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001391 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001392 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001393 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001394 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001395 ... [0, 1, ..., 9]
1396 ... '''
1397 >>> test = doctest.DocTestFinder().find(f)[0]
1398 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001399 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001400 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001401 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001402 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001403 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001404 Expected:
1405 [0, 1, ..., 9]
1406 Got:
1407 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001408 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001409
1410 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001411 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001412 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001413 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001414 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1415 ... [0, 1, ..., 9]
1416 ... '''
1417 >>> test = doctest.DocTestFinder().find(f)[0]
1418 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001419 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001420 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001421 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001422 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001423 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001424 Expected:
1425 [0, 1, ..., 9]
1426 Got:
1427 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001428 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001429
1430 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001431 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001432 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001433 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001434 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1435 ... [0, 1, ..., 9]
1436 ... '''
1437 >>> test = doctest.DocTestFinder().find(f)[0]
1438 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001439 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001440 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001441 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001442 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001443 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001444 Expected:
1445 [0, 1, ..., 9]
1446 Got:
1447 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001448 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001449
1450The option directive may be put on the line following the source, as
1451long as a continuation prompt is used:
1452
1453 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001454 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001455 ... ... # doctest: +ELLIPSIS
1456 ... [0, 1, ..., 9]
1457 ... '''
1458 >>> test = doctest.DocTestFinder().find(f)[0]
1459 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001460 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001461
Edward Loper74bca7a2004-08-12 02:27:44 +00001462For examples with multi-line source, the option directive may appear
1463at the end of any line:
1464
1465 >>> def f(x): r'''
1466 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001467 ... ... print(' ', x, end='', sep='')
1468 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001469 ...
1470 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001471 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1472 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001473 ... '''
1474 >>> test = doctest.DocTestFinder().find(f)[0]
1475 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001476 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001477
1478If more than one line of an example with multi-line source has an
1479option directive, then they are combined:
1480
1481 >>> def f(x): r'''
1482 ... Should fail (option directive not on the last line):
1483 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001484 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001485 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001486 ... '''
1487 >>> test = doctest.DocTestFinder().find(f)[0]
1488 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001489 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001490
1491It is an error to have a comment of the form ``# doctest:`` that is
1492*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1493``OPTION`` is an option that has been registered with
1494`register_option`:
1495
1496 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001497 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001498 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1499 Traceback (most recent call last):
1500 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1501
1502 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001503 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001504 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1505 Traceback (most recent call last):
1506 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1507
1508It is an error to use an option directive on a line that contains no
1509source:
1510
1511 >>> s = '>>> # doctest: +ELLIPSIS'
1512 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1513 Traceback (most recent call last):
1514 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 +00001515"""
1516
1517def test_testsource(): r"""
1518Unit tests for `testsource()`.
1519
1520The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001521test with that name in that module, and converts it to a script. The
1522example code is converted to regular Python code. The surrounding
1523words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001524
1525 >>> import test.test_doctest
1526 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001527 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001528 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001529 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001530 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001531 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001532 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001533 #
Edward Lopera5db6002004-08-12 02:41:30 +00001534 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001535 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001536
1537 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001538 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001539 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001540 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001541 ## 1
1542 ## 2
1543 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001544 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001545
1546 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001547 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001548 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001549 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001550 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001551 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001552 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001553 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001554 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001555"""
1556
1557def test_debug(): r"""
1558
1559Create a docstring that we want to debug:
1560
1561 >>> s = '''
1562 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001563 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001564 ... 12
1565 ... '''
1566
1567Create some fake stdin input, to feed to the debugger:
1568
Tim Peters8485b562004-08-04 18:46:34 +00001569 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001570 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001571
1572Run the debugger on the docstring, and then restore sys.stdin.
1573
Edward Loper2de91ba2004-08-27 02:07:46 +00001574 >>> try: doctest.debug_src(s)
1575 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001576 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001577 (Pdb) next
1578 12
Tim Peters8485b562004-08-04 18:46:34 +00001579 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001580 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001581 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001582 12
1583 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001584
1585"""
1586
Jim Fulton356fd192004-08-09 11:34:47 +00001587def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001588 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001589
Tim Peters413ced62004-08-09 15:43:47 +00001590 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001591 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001592 you use it. The doctest module changes sys.stdout so that it can
1593 capture program output. It also temporarily replaces pdb.set_trace
1594 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001595 see debugger output.
1596
1597 >>> doc = '''
1598 ... >>> x = 42
1599 ... >>> import pdb; pdb.set_trace()
1600 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001601 >>> parser = doctest.DocTestParser()
1602 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001603 >>> runner = doctest.DocTestRunner(verbose=False)
1604
1605 To demonstrate this, we'll create a fake standard input that
1606 captures our debugger input:
1607
1608 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001609 >>> real_stdin = sys.stdin
1610 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001611 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001612 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001613 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001614
Edward Loper2de91ba2004-08-27 02:07:46 +00001615 >>> try: runner.run(test)
1616 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001617 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001618 > <doctest foo[1]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001619 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001620 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001621 42
1622 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001623 TestResults(failed=0, attempted=2)
Jim Fulton356fd192004-08-09 11:34:47 +00001624
1625 You can also put pdb.set_trace in a function called from a test:
1626
1627 >>> def calls_set_trace():
1628 ... y=2
1629 ... import pdb; pdb.set_trace()
1630
1631 >>> doc = '''
1632 ... >>> x=1
1633 ... >>> calls_set_trace()
1634 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001635 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001636 >>> real_stdin = sys.stdin
1637 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001638 ... 'print(y)', # print data defined in the function
Jim Fulton356fd192004-08-09 11:34:47 +00001639 ... 'up', # out of function
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001640 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001641 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001642 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001643
Tim Peters50c6bdb2004-11-08 22:07:37 +00001644 >>> try:
1645 ... runner.run(test)
1646 ... finally:
1647 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001648 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001649 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1650 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001651 (Pdb) print(y)
Edward Loper2de91ba2004-08-27 02:07:46 +00001652 2
1653 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001654 > <doctest foo[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001655 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001656 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001657 1
1658 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001659 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001660
1661 During interactive debugging, source code is shown, even for
1662 doctest examples:
1663
1664 >>> doc = '''
1665 ... >>> def f(x):
1666 ... ... g(x*2)
1667 ... >>> def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001668 ... ... print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001669 ... ... import pdb; pdb.set_trace()
1670 ... >>> f(3)
1671 ... '''
1672 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1673 >>> real_stdin = sys.stdin
1674 >>> sys.stdin = _FakeInput([
1675 ... 'list', # list source from example 2
1676 ... 'next', # return from g()
1677 ... 'list', # list source from example 1
1678 ... 'next', # return from f()
1679 ... 'list', # list source from example 3
1680 ... 'continue', # stop debugging
1681 ... ''])
1682 >>> try: runner.run(test)
1683 ... finally: sys.stdin = real_stdin
1684 ... # doctest: +NORMALIZE_WHITESPACE
1685 --Return--
1686 > <doctest foo[1]>(3)g()->None
1687 -> import pdb; pdb.set_trace()
1688 (Pdb) list
1689 1 def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001690 2 print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001691 3 -> import pdb; pdb.set_trace()
1692 [EOF]
1693 (Pdb) next
1694 --Return--
1695 > <doctest foo[0]>(2)f()->None
1696 -> g(x*2)
1697 (Pdb) list
1698 1 def f(x):
1699 2 -> g(x*2)
1700 [EOF]
1701 (Pdb) next
1702 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001703 > <doctest foo[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001704 -> f(3)
1705 (Pdb) list
1706 1 -> f(3)
1707 [EOF]
1708 (Pdb) continue
1709 **********************************************************************
1710 File "foo.py", line 7, in foo
1711 Failed example:
1712 f(3)
1713 Expected nothing
1714 Got:
1715 9
Christian Heimes25bb7832008-01-11 16:17:00 +00001716 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001717 """
1718
Tim Peters50c6bdb2004-11-08 22:07:37 +00001719def test_pdb_set_trace_nested():
1720 """This illustrates more-demanding use of set_trace with nested functions.
1721
1722 >>> class C(object):
1723 ... def calls_set_trace(self):
1724 ... y = 1
1725 ... import pdb; pdb.set_trace()
1726 ... self.f1()
1727 ... y = 2
1728 ... def f1(self):
1729 ... x = 1
1730 ... self.f2()
1731 ... x = 2
1732 ... def f2(self):
1733 ... z = 1
1734 ... z = 2
1735
1736 >>> calls_set_trace = C().calls_set_trace
1737
1738 >>> doc = '''
1739 ... >>> a = 1
1740 ... >>> calls_set_trace()
1741 ... '''
1742 >>> parser = doctest.DocTestParser()
1743 >>> runner = doctest.DocTestRunner(verbose=False)
1744 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1745 >>> real_stdin = sys.stdin
1746 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001747 ... 'print(y)', # print data defined in the function
1748 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1749 ... 'up', 'print(x)',
1750 ... 'up', 'print(y)',
1751 ... 'up', 'print(foo)',
Tim Peters50c6bdb2004-11-08 22:07:37 +00001752 ... 'continue', # stop debugging
1753 ... ''])
1754
1755 >>> try:
1756 ... runner.run(test)
1757 ... finally:
1758 ... sys.stdin = real_stdin
Guido van Rossum4a625c32007-09-08 16:05:25 +00001759 ... # doctest: +REPORT_NDIFF
Tim Peters50c6bdb2004-11-08 22:07:37 +00001760 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1761 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001762 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001763 1
1764 (Pdb) step
1765 --Call--
1766 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1767 -> def f1(self):
1768 (Pdb) step
1769 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1770 -> x = 1
1771 (Pdb) step
1772 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1773 -> self.f2()
1774 (Pdb) step
1775 --Call--
1776 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1777 -> def f2(self):
1778 (Pdb) step
1779 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1780 -> z = 1
1781 (Pdb) step
1782 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1783 -> z = 2
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001784 (Pdb) print(z)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001785 1
1786 (Pdb) up
1787 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1788 -> self.f2()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001789 (Pdb) print(x)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001790 1
1791 (Pdb) up
1792 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1793 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001794 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001795 1
1796 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797 > <doctest foo[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001798 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001799 (Pdb) print(foo)
Guido van Rossumfd4a7de2007-09-05 03:26:38 +00001800 *** NameError: NameError("name 'foo' is not defined",)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001801 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001802 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001803"""
1804
Tim Peters19397e52004-08-06 22:02:59 +00001805def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001806 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001807
1808 We create a Suite by providing a module. A module can be provided
1809 by passing a module object:
1810
1811 >>> import unittest
1812 >>> import test.sample_doctest
1813 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1814 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001815 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001816
1817 We can also supply the module by name:
1818
1819 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1820 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001821 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001822
1823 We can use the current module:
1824
1825 >>> suite = test.sample_doctest.test_suite()
1826 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001827 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001828
1829 We can supply global variables. If we pass globs, they will be
1830 used instead of the module globals. Here we'll pass an empty
1831 globals, triggering an extra error:
1832
1833 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1834 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001835 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001836
1837 Alternatively, we can provide extra globals. Here we'll make an
1838 error go away by providing an extra global variable:
1839
1840 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1841 ... extraglobs={'y': 1})
1842 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001843 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001844
1845 You can pass option flags. Here we'll cause an extra error
1846 by disabling the blank-line feature:
1847
1848 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001849 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001850 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001851 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001852
Tim Peters1e277ee2004-08-07 05:37:52 +00001853 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001854
Jim Fultonf54bad42004-08-28 14:57:56 +00001855 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001856 ... import test.test_doctest
1857 ... test.test_doctest.sillySetup = True
1858
Jim Fultonf54bad42004-08-28 14:57:56 +00001859 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001860 ... import test.test_doctest
1861 ... del test.test_doctest.sillySetup
1862
1863 Here, we installed a silly variable that the test expects:
1864
1865 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1866 ... setUp=setUp, tearDown=tearDown)
1867 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001868 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001869
1870 But the tearDown restores sanity:
1871
1872 >>> import test.test_doctest
1873 >>> test.test_doctest.sillySetup
1874 Traceback (most recent call last):
1875 ...
1876 AttributeError: 'module' object has no attribute 'sillySetup'
1877
Jim Fultonf54bad42004-08-28 14:57:56 +00001878 The setUp and tearDown funtions are passed test objects. Here
1879 we'll use the setUp function to supply the missing variable y:
1880
1881 >>> def setUp(test):
1882 ... test.globs['y'] = 1
1883
1884 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1885 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001886 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00001887
1888 Here, we didn't need to use a tearDown function because we
1889 modified the test globals, which are a copy of the
1890 sample_doctest module dictionary. The test globals are
1891 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001892 """
1893
1894def test_DocFileSuite():
1895 """We can test tests found in text files using a DocFileSuite.
1896
1897 We create a suite by providing the names of one or more text
1898 files that include examples:
1899
1900 >>> import unittest
1901 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001902 ... 'test_doctest2.txt',
1903 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00001904 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001905 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001906
1907 The test files are looked for in the directory containing the
1908 calling module. A package keyword argument can be provided to
1909 specify a different relative location.
1910
1911 >>> import unittest
1912 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1913 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001914 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001915 ... package='test')
1916 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001917 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001918
Guido van Rossumcd4d4522007-11-22 00:30:02 +00001919 Support for using a package's __loader__.get_data() is also
1920 provided.
1921
1922 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001923 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00001924 >>> if not hasattr(test, '__loader__'):
1925 ... test.__loader__ = pkgutil.get_loader(test)
1926 ... added_loader = True
1927 >>> try:
1928 ... suite = doctest.DocFileSuite('test_doctest.txt',
1929 ... 'test_doctest2.txt',
1930 ... 'test_doctest4.txt',
1931 ... package='test')
1932 ... suite.run(unittest.TestResult())
1933 ... finally:
1934 ... if added_loader:
1935 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001936 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00001937
Edward Loper0273f5b2004-09-18 20:27:04 +00001938 '/' should be used as a path separator. It will be converted
1939 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001940
1941 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1942 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001943 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001944
Edward Loper0273f5b2004-09-18 20:27:04 +00001945 If DocFileSuite is used from an interactive session, then files
1946 are resolved relative to the directory of sys.argv[0]:
1947
Christian Heimes45f9af32007-11-27 21:50:00 +00001948 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00001949 >>> save_argv = sys.argv
1950 >>> sys.argv = [test.test_doctest.__file__]
1951 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00001952 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00001953 >>> sys.argv = save_argv
1954
Edward Loper052d0cd2004-09-19 17:19:33 +00001955 By setting `module_relative=False`, os-specific paths may be
1956 used (including absolute paths and paths relative to the
1957 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00001958
1959 >>> # Get the absolute path of the test package.
1960 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
1961 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
1962
1963 >>> # Use it to find the absolute path of test_doctest.txt.
1964 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
1965
Edward Loper052d0cd2004-09-19 17:19:33 +00001966 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00001967 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001968 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00001969
Edward Loper052d0cd2004-09-19 17:19:33 +00001970 It is an error to specify `package` when `module_relative=False`:
1971
1972 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
1973 ... package='test')
1974 Traceback (most recent call last):
1975 ValueError: Package may only be specified for module-relative paths.
1976
Tim Peters19397e52004-08-06 22:02:59 +00001977 You can specify initial global variables:
1978
1979 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1980 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001981 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001982 ... globs={'favorite_color': 'blue'})
1983 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001984 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001985
1986 In this case, we supplied a missing favorite color. You can
1987 provide doctest options:
1988
1989 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1990 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001991 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001992 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1993 ... globs={'favorite_color': 'blue'})
1994 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001995 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001996
1997 And, you can provide setUp and tearDown functions:
1998
Jim Fultonf54bad42004-08-28 14:57:56 +00001999 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002000 ... import test.test_doctest
2001 ... test.test_doctest.sillySetup = True
2002
Jim Fultonf54bad42004-08-28 14:57:56 +00002003 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002004 ... import test.test_doctest
2005 ... del test.test_doctest.sillySetup
2006
2007 Here, we installed a silly variable that the test expects:
2008
2009 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2010 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002011 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002012 ... setUp=setUp, tearDown=tearDown)
2013 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002014 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002015
2016 But the tearDown restores sanity:
2017
2018 >>> import test.test_doctest
2019 >>> test.test_doctest.sillySetup
2020 Traceback (most recent call last):
2021 ...
2022 AttributeError: 'module' object has no attribute 'sillySetup'
2023
Jim Fultonf54bad42004-08-28 14:57:56 +00002024 The setUp and tearDown funtions are passed test objects.
2025 Here, we'll use a setUp function to set the favorite color in
2026 test_doctest.txt:
2027
2028 >>> def setUp(test):
2029 ... test.globs['favorite_color'] = 'blue'
2030
2031 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2032 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002033 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002034
2035 Here, we didn't need to use a tearDown function because we
2036 modified the test globals. The test globals are
2037 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002038
Fred Drake7c404a42004-12-21 23:46:34 +00002039 Tests in a file run using `DocFileSuite` can also access the
2040 `__file__` global, which is set to the name of the file
2041 containing the tests:
2042
2043 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2044 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002045 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002046
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002047 If the tests contain non-ASCII characters, we have to specify which
2048 encoding the file is encoded with. We do so by using the `encoding`
2049 parameter:
2050
2051 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2052 ... 'test_doctest2.txt',
2053 ... 'test_doctest4.txt',
2054 ... encoding='utf-8')
2055 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002056 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002057
Jim Fultonf54bad42004-08-28 14:57:56 +00002058 """
Tim Peters19397e52004-08-06 22:02:59 +00002059
Jim Fulton07a349c2004-08-22 14:10:00 +00002060def test_trailing_space_in_test():
2061 """
Tim Petersa7def722004-08-23 22:13:22 +00002062 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002063
Jim Fulton07a349c2004-08-22 14:10:00 +00002064 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002065 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002066 foo \n
2067 """
Tim Peters19397e52004-08-06 22:02:59 +00002068
Jim Fultonf54bad42004-08-28 14:57:56 +00002069
2070def test_unittest_reportflags():
2071 """Default unittest reporting flags can be set to control reporting
2072
2073 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2074 only the first failure of each test. First, we'll look at the
2075 output without the flag. The file test_doctest.txt file has two
2076 tests. They both fail if blank lines are disabled:
2077
2078 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2079 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2080 >>> import unittest
2081 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002082 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002083 Traceback ...
2084 Failed example:
2085 favorite_color
2086 ...
2087 Failed example:
2088 if 1:
2089 ...
2090
2091 Note that we see both failures displayed.
2092
2093 >>> old = doctest.set_unittest_reportflags(
2094 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2095
2096 Now, when we run the test:
2097
2098 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002099 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002100 Traceback ...
2101 Failed example:
2102 favorite_color
2103 Exception raised:
2104 ...
2105 NameError: name 'favorite_color' is not defined
2106 <BLANKLINE>
2107 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002108
Jim Fultonf54bad42004-08-28 14:57:56 +00002109 We get only the first failure.
2110
2111 If we give any reporting options when we set up the tests,
2112 however:
2113
2114 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2115 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2116
2117 Then the default eporting options are ignored:
2118
2119 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002120 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002121 Traceback ...
2122 Failed example:
2123 favorite_color
2124 ...
2125 Failed example:
2126 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002127 print('a')
2128 print()
2129 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002130 Differences (ndiff with -expected +actual):
2131 a
2132 - <BLANKLINE>
2133 +
2134 b
2135 <BLANKLINE>
2136 <BLANKLINE>
2137
2138
2139 Test runners can restore the formatting flags after they run:
2140
2141 >>> ignored = doctest.set_unittest_reportflags(old)
2142
2143 """
2144
Edward Loper052d0cd2004-09-19 17:19:33 +00002145def test_testfile(): r"""
2146Tests for the `testfile()` function. This function runs all the
2147doctest examples in a given file. In its simple invokation, it is
2148called with the name of a file, which is taken to be relative to the
2149calling module. The return value is (#failures, #tests).
2150
Florent Xicluna59250852010-02-27 14:21:57 +00002151We don't want `-v` in sys.argv for these tests.
2152
2153 >>> save_argv = sys.argv
2154 >>> if '-v' in sys.argv:
2155 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2156
2157
Edward Loper052d0cd2004-09-19 17:19:33 +00002158 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2159 **********************************************************************
2160 File "...", line 6, in test_doctest.txt
2161 Failed example:
2162 favorite_color
2163 Exception raised:
2164 ...
2165 NameError: name 'favorite_color' is not defined
2166 **********************************************************************
2167 1 items had failures:
2168 1 of 2 in test_doctest.txt
2169 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002170 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002171 >>> doctest.master = None # Reset master.
2172
2173(Note: we'll be clearing doctest.master after each call to
2174`doctest.testfile`, to supress warnings about multiple tests with the
2175same name.)
2176
2177Globals may be specified with the `globs` and `extraglobs` parameters:
2178
2179 >>> globs = {'favorite_color': 'blue'}
2180 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002181 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002182 >>> doctest.master = None # Reset master.
2183
2184 >>> extraglobs = {'favorite_color': 'red'}
2185 >>> doctest.testfile('test_doctest.txt', globs=globs,
2186 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2187 **********************************************************************
2188 File "...", line 6, in test_doctest.txt
2189 Failed example:
2190 favorite_color
2191 Expected:
2192 'blue'
2193 Got:
2194 'red'
2195 **********************************************************************
2196 1 items had failures:
2197 1 of 2 in test_doctest.txt
2198 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002199 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002200 >>> doctest.master = None # Reset master.
2201
2202The file may be made relative to a given module or package, using the
2203optional `module_relative` parameter:
2204
2205 >>> doctest.testfile('test_doctest.txt', globs=globs,
2206 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002207 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002208 >>> doctest.master = None # Reset master.
2209
2210Verbosity can be increased with the optional `verbose` paremter:
2211
2212 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2213 Trying:
2214 favorite_color
2215 Expecting:
2216 'blue'
2217 ok
2218 Trying:
2219 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002220 print('a')
2221 print()
2222 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002223 Expecting:
2224 a
2225 <BLANKLINE>
2226 b
2227 ok
2228 1 items passed all tests:
2229 2 tests in test_doctest.txt
2230 2 tests in 1 items.
2231 2 passed and 0 failed.
2232 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002233 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002234 >>> doctest.master = None # Reset master.
2235
2236The name of the test may be specified with the optional `name`
2237parameter:
2238
2239 >>> doctest.testfile('test_doctest.txt', name='newname')
2240 ... # doctest: +ELLIPSIS
2241 **********************************************************************
2242 File "...", line 6, in newname
2243 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002244 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002245 >>> doctest.master = None # Reset master.
2246
2247The summary report may be supressed with the optional `report`
2248parameter:
2249
2250 >>> doctest.testfile('test_doctest.txt', report=False)
2251 ... # doctest: +ELLIPSIS
2252 **********************************************************************
2253 File "...", line 6, in test_doctest.txt
2254 Failed example:
2255 favorite_color
2256 Exception raised:
2257 ...
2258 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002259 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002260 >>> doctest.master = None # Reset master.
2261
2262The optional keyword argument `raise_on_error` can be used to raise an
2263exception on the first error (which may be useful for postmortem
2264debugging):
2265
2266 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2267 ... # doctest: +ELLIPSIS
2268 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002269 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002270 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002271
2272If the tests contain non-ASCII characters, the tests might fail, since
2273it's unknown which encoding is used. The encoding can be specified
2274using the optional keyword argument `encoding`:
2275
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002276 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002277 **********************************************************************
2278 File "...", line 7, in test_doctest4.txt
2279 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002280 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002281 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002282 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002283 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002284 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002285 **********************************************************************
2286 ...
2287 **********************************************************************
2288 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002289 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002290 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002291 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002292 >>> doctest.master = None # Reset master.
2293
2294 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002295 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002296 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002297
2298Test the verbose output:
2299
2300 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2301 Trying:
2302 'föö'
2303 Expecting:
2304 'f\xf6\xf6'
2305 ok
2306 Trying:
2307 'bąr'
2308 Expecting:
2309 'b\u0105r'
2310 ok
2311 1 items passed all tests:
2312 2 tests in test_doctest4.txt
2313 2 tests in 1 items.
2314 2 passed and 0 failed.
2315 Test passed.
2316 TestResults(failed=0, attempted=2)
2317 >>> doctest.master = None # Reset master.
2318 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002319"""
2320
R. David Murray58641de2009-06-12 15:33:19 +00002321def test_testmod(): r"""
2322Tests for the testmod function. More might be useful, but for now we're just
2323testing the case raised by Issue 6195, where trying to doctest a C module would
2324fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2325out of the binary module.
2326
2327 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002328 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002329 TestResults(failed=0, attempted=0)
2330"""
2331
Tim Peters8485b562004-08-04 18:46:34 +00002332######################################################################
2333## Main
2334######################################################################
2335
2336def test_main():
2337 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002338 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002339 # Check the doctest cases defined here:
2340 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002341 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002342
Guido van Rossum34d19282007-08-09 01:03:29 +00002343import trace, sys, re, io
Tim Peters8485b562004-08-04 18:46:34 +00002344def test_coverage(coverdir):
2345 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2346 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002347 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002348 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002349 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002350 r.write_results(show_missing=True, summary=True,
2351 coverdir=coverdir)
2352
2353if __name__ == '__main__':
2354 if '-c' in sys.argv:
2355 test_coverage('/tmp/doctest.cover')
2356 else:
2357 test_main()