blob: 07a2997ae2f6ece76542447fe4a78299625665ed [file] [log] [blame]
Florent Xicluna2a903b22010-02-27 13:31:23 +00001# -*- coding: utf-8 -*-
Tim Peters8485b562004-08-04 18:46:34 +00002"""
3Test script for doctest.
4"""
5
Florent Xicluna6257a7b2010-03-31 22:01:03 +00006import sys
Barry Warsaw04f357c2002-07-23 19:04:11 +00007from test import test_support
Tim Peters8485b562004-08-04 18:46:34 +00008import doctest
9
Nick Coghlana2053472008-12-14 10:54:50 +000010# NOTE: There are some additional tests relating to interaction with
11# zipimport in the test_zipimport_support test module.
12
Tim Peters8485b562004-08-04 18:46:34 +000013######################################################################
14## Sample Objects (used by test cases)
15######################################################################
16
17def sample_func(v):
18 """
Tim Peters19397e52004-08-06 22:02:59 +000019 Blah blah
20
Tim Peters8485b562004-08-04 18:46:34 +000021 >>> print sample_func(22)
22 44
Tim Peters19397e52004-08-06 22:02:59 +000023
24 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000025 """
26 return v+v
27
28class SampleClass:
29 """
30 >>> print 1
31 1
Edward Loper4ae900f2004-09-21 03:20:34 +000032
33 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
34 >>>
35 ...
36
37 Multiline example:
38 >>> sc = SampleClass(3)
39 >>> for i in range(10):
40 ... sc = sc.double()
41 ... print sc.get(),
42 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000043 """
44 def __init__(self, val):
45 """
46 >>> print SampleClass(12).get()
47 12
48 """
49 self.val = val
50
51 def double(self):
52 """
53 >>> print SampleClass(12).double().get()
54 24
55 """
56 return SampleClass(self.val + self.val)
57
58 def get(self):
59 """
60 >>> print SampleClass(-5).get()
61 -5
62 """
63 return self.val
64
65 def a_staticmethod(v):
66 """
67 >>> print SampleClass.a_staticmethod(10)
68 11
69 """
70 return v+1
71 a_staticmethod = staticmethod(a_staticmethod)
72
73 def a_classmethod(cls, v):
74 """
75 >>> print SampleClass.a_classmethod(10)
76 12
77 >>> print SampleClass(0).a_classmethod(10)
78 12
79 """
80 return v+2
81 a_classmethod = classmethod(a_classmethod)
82
83 a_property = property(get, doc="""
84 >>> print SampleClass(22).a_property
85 22
86 """)
87
88 class NestedClass:
89 """
90 >>> x = SampleClass.NestedClass(5)
91 >>> y = x.square()
92 >>> print y.get()
93 25
94 """
95 def __init__(self, val=0):
96 """
97 >>> print SampleClass.NestedClass().get()
98 0
99 """
100 self.val = val
101 def square(self):
102 return SampleClass.NestedClass(self.val*self.val)
103 def get(self):
104 return self.val
105
106class SampleNewStyleClass(object):
107 r"""
108 >>> print '1\n2\n3'
109 1
110 2
111 3
112 """
113 def __init__(self, val):
114 """
115 >>> print SampleNewStyleClass(12).get()
116 12
117 """
118 self.val = val
119
120 def double(self):
121 """
122 >>> print SampleNewStyleClass(12).double().get()
123 24
124 """
125 return SampleNewStyleClass(self.val + self.val)
126
127 def get(self):
128 """
129 >>> print SampleNewStyleClass(-5).get()
130 -5
131 """
132 return self.val
133
134######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000135## Fake stdin (for testing interactive debugging)
136######################################################################
137
138class _FakeInput:
139 """
140 A fake input stream for pdb's interactive debugger. Whenever a
141 line is read, print it (to simulate the user typing it), and then
142 return it. The set of lines to return is specified in the
143 constructor; they should not have trailing newlines.
144 """
145 def __init__(self, lines):
146 self.lines = lines
147
148 def readline(self):
149 line = self.lines.pop(0)
150 print line
151 return line+'\n'
152
153######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000154## Test Cases
155######################################################################
156
157def test_Example(): r"""
158Unit tests for the `Example` class.
159
Edward Lopera6b68322004-08-26 00:05:43 +0000160Example is a simple container class that holds:
161 - `source`: A source string.
162 - `want`: An expected output string.
163 - `exc_msg`: An expected exception message string (or None if no
164 exception is expected).
165 - `lineno`: A line number (within the docstring).
166 - `indent`: The example's indentation in the input string.
167 - `options`: An option dictionary, mapping option flags to True or
168 False.
Tim Peters8485b562004-08-04 18:46:34 +0000169
Edward Lopera6b68322004-08-26 00:05:43 +0000170These attributes are set by the constructor. `source` and `want` are
171required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000172
Edward Lopera6b68322004-08-26 00:05:43 +0000173 >>> example = doctest.Example('print 1', '1\n')
174 >>> (example.source, example.want, example.exc_msg,
175 ... example.lineno, example.indent, example.options)
176 ('print 1\n', '1\n', None, 0, 0, {})
177
178The first three attributes (`source`, `want`, and `exc_msg`) may be
179specified positionally; the remaining arguments should be specified as
180keyword arguments:
181
182 >>> exc_msg = 'IndexError: pop from an empty list'
183 >>> example = doctest.Example('[].pop()', '', exc_msg,
184 ... lineno=5, indent=4,
185 ... options={doctest.ELLIPSIS: True})
186 >>> (example.source, example.want, example.exc_msg,
187 ... example.lineno, example.indent, example.options)
188 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
189
190The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000191
Tim Petersbb431472004-08-09 03:51:46 +0000192 Source spans a single line: no terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000193 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000194 >>> e.source, e.want
195 ('print 1\n', '1\n')
196
Edward Lopera6b68322004-08-26 00:05:43 +0000197 >>> e = doctest.Example('print 1\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000198 >>> e.source, e.want
199 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000200
Tim Petersbb431472004-08-09 03:51:46 +0000201 Source spans multiple lines: require terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000202 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000203 >>> e.source, e.want
204 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000205
Edward Lopera6b68322004-08-26 00:05:43 +0000206 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000207 >>> e.source, e.want
208 ('print 1;\nprint 2\n', '1\n2\n')
209
Edward Lopera6b68322004-08-26 00:05:43 +0000210 Empty source string (which should never appear in real examples)
211 >>> e = doctest.Example('', '')
212 >>> e.source, e.want
213 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000214
Edward Lopera6b68322004-08-26 00:05:43 +0000215The constructor normalizes the `want` string to end in a newline,
216unless it's the empty string:
217
218 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000219 >>> e.source, e.want
220 ('print 1\n', '1\n')
221
Edward Lopera6b68322004-08-26 00:05:43 +0000222 >>> e = doctest.Example('print 1', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000223 >>> e.source, e.want
224 ('print 1\n', '1\n')
225
Edward Lopera6b68322004-08-26 00:05:43 +0000226 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000227 >>> e.source, e.want
228 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000229
230The constructor normalizes the `exc_msg` string to end in a newline,
231unless it's `None`:
232
233 Message spans one line
234 >>> exc_msg = 'IndexError: pop from an empty list'
235 >>> e = doctest.Example('[].pop()', '', exc_msg)
236 >>> e.exc_msg
237 'IndexError: pop from an empty list\n'
238
239 >>> exc_msg = 'IndexError: pop from an empty list\n'
240 >>> e = doctest.Example('[].pop()', '', exc_msg)
241 >>> e.exc_msg
242 'IndexError: pop from an empty list\n'
243
244 Message spans multiple lines
245 >>> exc_msg = 'ValueError: 1\n 2'
246 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
247 >>> e.exc_msg
248 'ValueError: 1\n 2\n'
249
250 >>> exc_msg = 'ValueError: 1\n 2\n'
251 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
252 >>> e.exc_msg
253 'ValueError: 1\n 2\n'
254
255 Empty (but non-None) exception message (which should never appear
256 in real examples)
257 >>> exc_msg = ''
258 >>> e = doctest.Example('raise X()', '', exc_msg)
259 >>> e.exc_msg
260 '\n'
Antoine Pitrou6c3f4a82011-12-18 20:20:17 +0100261
262Compare `Example`:
263 >>> example = doctest.Example('print 1', '1\n')
264 >>> same_example = doctest.Example('print 1', '1\n')
265 >>> other_example = doctest.Example('print 42', '42\n')
266 >>> example == same_example
267 True
268 >>> example != same_example
269 False
270 >>> hash(example) == hash(same_example)
271 True
272 >>> example == other_example
273 False
274 >>> example != other_example
275 True
Tim Peters8485b562004-08-04 18:46:34 +0000276"""
277
278def test_DocTest(): r"""
279Unit tests for the `DocTest` class.
280
281DocTest is a collection of examples, extracted from a docstring, along
282with information about where the docstring comes from (a name,
283filename, and line number). The docstring is parsed by the `DocTest`
284constructor:
285
286 >>> docstring = '''
287 ... >>> print 12
288 ... 12
289 ...
290 ... Non-example text.
291 ...
292 ... >>> print 'another\example'
293 ... another
294 ... example
295 ... '''
296 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000297 >>> parser = doctest.DocTestParser()
298 >>> test = parser.get_doctest(docstring, globs, 'some_test',
299 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000300 >>> print test
301 <DocTest some_test from some_file:20 (2 examples)>
302 >>> len(test.examples)
303 2
304 >>> e1, e2 = test.examples
305 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000306 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000307 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000308 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000309
310Source information (name, filename, and line number) is available as
311attributes on the doctest object:
312
313 >>> (test.name, test.filename, test.lineno)
314 ('some_test', 'some_file', 20)
315
316The line number of an example within its containing file is found by
317adding the line number of the example and the line number of its
318containing test:
319
320 >>> test.lineno + e1.lineno
321 21
322 >>> test.lineno + e2.lineno
323 26
324
325If the docstring contains inconsistant leading whitespace in the
326expected output of an example, then `DocTest` will raise a ValueError:
327
328 >>> docstring = r'''
329 ... >>> print 'bad\nindentation'
330 ... bad
331 ... indentation
332 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000333 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000334 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000335 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000336
337If the docstring contains inconsistent leading whitespace on
338continuation lines, then `DocTest` will raise a ValueError:
339
340 >>> docstring = r'''
341 ... >>> print ('bad indentation',
342 ... ... 2)
343 ... ('bad', 'indentation')
344 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000345 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000346 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000347 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
Tim Peters8485b562004-08-04 18:46:34 +0000348
349If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
350will raise a ValueError:
351
352 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000353 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000354 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000355 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
356
357If there's no blank space after a PS2 prompt ('...'), then `DocTest`
358will raise a ValueError:
359
360 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000361 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000362 Traceback (most recent call last):
363 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
364
Antoine Pitrou7a3d8ae2011-12-18 19:27:45 +0100365Compare `DocTest`:
366
367 >>> docstring = '''
368 ... >>> print 12
369 ... 12
370 ... '''
371 >>> test = parser.get_doctest(docstring, globs, 'some_test',
372 ... 'some_test', 20)
373 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
374 ... 'some_test', 20)
375 >>> test == same_test
376 True
377 >>> test != same_test
378 False
Antoine Pitrou6c3f4a82011-12-18 20:20:17 +0100379 >>> hash(test) == hash(same_test)
380 True
Antoine Pitrou7a3d8ae2011-12-18 19:27:45 +0100381 >>> docstring = '''
382 ... >>> print 42
383 ... 42
384 ... '''
385 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
386 ... 'other_file', 10)
387 >>> test == other_test
388 False
389 >>> test != other_test
390 True
391
392Compare `DocTestCase`:
393
394 >>> DocTestCase = doctest.DocTestCase
395 >>> test_case = DocTestCase(test)
396 >>> same_test_case = DocTestCase(same_test)
397 >>> other_test_case = DocTestCase(other_test)
398 >>> test_case == same_test_case
399 True
400 >>> test_case != same_test_case
401 False
Antoine Pitrou6c3f4a82011-12-18 20:20:17 +0100402 >>> hash(test_case) == hash(same_test_case)
403 True
Antoine Pitrou7a3d8ae2011-12-18 19:27:45 +0100404 >>> test == other_test_case
405 False
406 >>> test != other_test_case
407 True
408
Tim Peters8485b562004-08-04 18:46:34 +0000409"""
410
Tim Peters8485b562004-08-04 18:46:34 +0000411def test_DocTestFinder(): r"""
412Unit tests for the `DocTestFinder` class.
413
414DocTestFinder is used to extract DocTests from an object's docstring
415and the docstrings of its contained objects. It can be used with
416modules, functions, classes, methods, staticmethods, classmethods, and
417properties.
418
419Finding Tests in Functions
420~~~~~~~~~~~~~~~~~~~~~~~~~~
421For a function whose docstring contains examples, DocTestFinder.find()
422will return a single test (for that function's docstring):
423
Tim Peters8485b562004-08-04 18:46:34 +0000424 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000425
426We'll simulate a __file__ attr that ends in pyc:
427
428 >>> import test.test_doctest
429 >>> old = test.test_doctest.__file__
430 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
431
Tim Peters8485b562004-08-04 18:46:34 +0000432 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000433
Edward Loper74bca7a2004-08-12 02:27:44 +0000434 >>> print tests # doctest: +ELLIPSIS
Florent Xicluna2a903b22010-02-27 13:31:23 +0000435 [<DocTest sample_func from ...:17 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000436
Tim Peters4de7c5c2004-08-23 22:38:05 +0000437The exact name depends on how test_doctest was invoked, so allow for
438leading path components.
439
440 >>> tests[0].filename # doctest: +ELLIPSIS
441 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000442
443 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000444
Jim Fulton07a349c2004-08-22 14:10:00 +0000445
Tim Peters8485b562004-08-04 18:46:34 +0000446 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000447 >>> (e.source, e.want, e.lineno)
448 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000449
Edward Loper32ddbf72004-09-13 05:47:24 +0000450By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000451
452 >>> def no_docstring(v):
453 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000454 >>> finder.find(no_docstring)
455 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000456
457However, the optional argument `exclude_empty` to the DocTestFinder
458constructor can be used to exclude tests for objects with empty
459docstrings:
460
461 >>> def no_docstring(v):
462 ... pass
463 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
464 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000465 []
466
467If the function has a docstring with no examples, then a test with no
468examples is returned. (This lets `DocTestRunner` collect statistics
469about which functions have no tests -- but is that useful? And should
470an empty test also be created when there's no docstring?)
471
472 >>> def no_examples(v):
473 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000474 >>> finder.find(no_examples) # doctest: +ELLIPSIS
475 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000476
477Finding Tests in Classes
478~~~~~~~~~~~~~~~~~~~~~~~~
479For a class, DocTestFinder will create a test for the class's
480docstring, and will recursively explore its contents, including
481methods, classmethods, staticmethods, properties, and nested classes.
482
483 >>> finder = doctest.DocTestFinder()
484 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000485 >>> for t in tests:
486 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000487 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000488 3 SampleClass.NestedClass
489 1 SampleClass.NestedClass.__init__
490 1 SampleClass.__init__
491 2 SampleClass.a_classmethod
492 1 SampleClass.a_property
493 1 SampleClass.a_staticmethod
494 1 SampleClass.double
495 1 SampleClass.get
496
497New-style classes are also supported:
498
499 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000500 >>> for t in tests:
501 ... print '%2s %s' % (len(t.examples), t.name)
502 1 SampleNewStyleClass
503 1 SampleNewStyleClass.__init__
504 1 SampleNewStyleClass.double
505 1 SampleNewStyleClass.get
506
507Finding Tests in Modules
508~~~~~~~~~~~~~~~~~~~~~~~~
509For a module, DocTestFinder will create a test for the class's
510docstring, and will recursively explore its contents, including
511functions, classes, and the `__test__` dictionary, if it exists:
512
513 >>> # A module
Christian Heimesc756d002007-11-27 21:34:01 +0000514 >>> import types
515 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000516 >>> def triple(val):
517 ... '''
Edward Loper4ae900f2004-09-21 03:20:34 +0000518 ... >>> print triple(11)
Tim Peters8485b562004-08-04 18:46:34 +0000519 ... 33
520 ... '''
521 ... return val*3
522 >>> m.__dict__.update({
523 ... 'sample_func': sample_func,
524 ... 'SampleClass': SampleClass,
525 ... '__doc__': '''
526 ... Module docstring.
527 ... >>> print 'module'
528 ... module
529 ... ''',
530 ... '__test__': {
531 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
532 ... 'c': triple}})
533
534 >>> finder = doctest.DocTestFinder()
535 >>> # Use module=test.test_doctest, to prevent doctest from
536 >>> # ignoring the objects since they weren't defined in m.
537 >>> import test.test_doctest
538 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000539 >>> for t in tests:
540 ... print '%2s %s' % (len(t.examples), t.name)
541 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000542 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000543 3 some_module.SampleClass.NestedClass
544 1 some_module.SampleClass.NestedClass.__init__
545 1 some_module.SampleClass.__init__
546 2 some_module.SampleClass.a_classmethod
547 1 some_module.SampleClass.a_property
548 1 some_module.SampleClass.a_staticmethod
549 1 some_module.SampleClass.double
550 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000551 1 some_module.__test__.c
552 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000553 1 some_module.sample_func
554
555Duplicate Removal
556~~~~~~~~~~~~~~~~~
557If a single object is listed twice (under different names), then tests
558will only be generated for it once:
559
Tim Petersf3f57472004-08-08 06:11:48 +0000560 >>> from test import doctest_aliases
Amaury Forgeot d'Arcf81ff982009-06-14 21:20:40 +0000561 >>> assert doctest_aliases.TwoNames.f
562 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000563 >>> tests = excl_empty_finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000564 >>> print len(tests)
565 2
566 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000567 test.doctest_aliases.TwoNames
568
569 TwoNames.f and TwoNames.g are bound to the same object.
570 We can't guess which will be found in doctest's traversal of
571 TwoNames.__dict__ first, so we have to allow for either.
572
573 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000574 True
575
Tim Petersbf0400a2006-06-05 01:43:03 +0000576Empty Tests
577~~~~~~~~~~~
578By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000579
Tim Petersbf0400a2006-06-05 01:43:03 +0000580 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000581 >>> for t in tests:
582 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000583 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000584 3 SampleClass.NestedClass
585 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000586 1 SampleClass.__init__
Tim Petersbf0400a2006-06-05 01:43:03 +0000587 2 SampleClass.a_classmethod
588 1 SampleClass.a_property
589 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000590 1 SampleClass.double
591 1 SampleClass.get
592
593By default, that excluded objects with no doctests. exclude_empty=False
594tells it to include (empty) tests for objects with no doctests. This feature
595is really to support backward compatibility in what doctest.master.summarize()
596displays.
597
Tim Petersbf0400a2006-06-05 01:43:03 +0000598 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000599 >>> for t in tests:
600 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000601 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000602 3 SampleClass.NestedClass
603 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000604 0 SampleClass.NestedClass.get
605 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000606 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000607 2 SampleClass.a_classmethod
608 1 SampleClass.a_property
609 1 SampleClass.a_staticmethod
610 1 SampleClass.double
611 1 SampleClass.get
612
Tim Peters8485b562004-08-04 18:46:34 +0000613Turning off Recursion
614~~~~~~~~~~~~~~~~~~~~~
615DocTestFinder can be told not to look for tests in contained objects
616using the `recurse` flag:
617
618 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000619 >>> for t in tests:
620 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000621 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000622
623Line numbers
624~~~~~~~~~~~~
625DocTestFinder finds the line number of each example:
626
627 >>> def f(x):
628 ... '''
629 ... >>> x = 12
630 ...
631 ... some text
632 ...
633 ... >>> # examples are not created for comments & bare prompts.
634 ... >>>
635 ... ...
636 ...
637 ... >>> for x in range(10):
638 ... ... print x,
639 ... 0 1 2 3 4 5 6 7 8 9
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000640 ... >>> x//2
Edward Loperb51b2342004-08-17 16:37:12 +0000641 ... 6
642 ... '''
643 >>> test = doctest.DocTestFinder().find(f)[0]
644 >>> [e.lineno for e in test.examples]
645 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000646"""
647
Edward Loper00f8da72004-08-26 18:05:07 +0000648def test_DocTestParser(): r"""
649Unit tests for the `DocTestParser` class.
650
651DocTestParser is used to parse docstrings containing doctest examples.
652
653The `parse` method divides a docstring into examples and intervening
654text:
655
656 >>> s = '''
657 ... >>> x, y = 2, 3 # no output expected
658 ... >>> if 1:
659 ... ... print x
660 ... ... print y
661 ... 2
662 ... 3
663 ...
664 ... Some text.
665 ... >>> x+y
666 ... 5
667 ... '''
668 >>> parser = doctest.DocTestParser()
669 >>> for piece in parser.parse(s):
670 ... if isinstance(piece, doctest.Example):
671 ... print 'Example:', (piece.source, piece.want, piece.lineno)
672 ... else:
673 ... print ' Text:', `piece`
674 Text: '\n'
675 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
676 Text: ''
677 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
678 Text: '\nSome text.\n'
679 Example: ('x+y\n', '5\n', 9)
680 Text: ''
681
682The `get_examples` method returns just the examples:
683
684 >>> for piece in parser.get_examples(s):
685 ... print (piece.source, piece.want, piece.lineno)
686 ('x, y = 2, 3 # no output expected\n', '', 1)
687 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
688 ('x+y\n', '5\n', 9)
689
690The `get_doctest` method creates a Test from the examples, along with the
691given arguments:
692
693 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
694 >>> (test.name, test.filename, test.lineno)
695 ('name', 'filename', 5)
696 >>> for piece in test.examples:
697 ... print (piece.source, piece.want, piece.lineno)
698 ('x, y = 2, 3 # no output expected\n', '', 1)
699 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
700 ('x+y\n', '5\n', 9)
701"""
702
Tim Peters8485b562004-08-04 18:46:34 +0000703class test_DocTestRunner:
704 def basics(): r"""
705Unit tests for the `DocTestRunner` class.
706
707DocTestRunner is used to run DocTest test cases, and to accumulate
708statistics. Here's a simple DocTest case we can use:
709
710 >>> def f(x):
711 ... '''
712 ... >>> x = 12
713 ... >>> print x
714 ... 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000715 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000716 ... 6
717 ... '''
718 >>> test = doctest.DocTestFinder().find(f)[0]
719
720The main DocTestRunner interface is the `run` method, which runs a
721given DocTest case in a given namespace (globs). It returns a tuple
722`(f,t)`, where `f` is the number of failed tests and `t` is the number
723of tried tests.
724
725 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000726 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000727
728If any example produces incorrect output, then the test runner reports
729the failure and proceeds to the next example:
730
731 >>> def f(x):
732 ... '''
733 ... >>> x = 12
734 ... >>> print x
735 ... 14
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000736 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000737 ... 6
738 ... '''
739 >>> test = doctest.DocTestFinder().find(f)[0]
740 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000741 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000742 Trying:
743 x = 12
744 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000745 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000746 Trying:
747 print x
748 Expecting:
749 14
Tim Peters8485b562004-08-04 18:46:34 +0000750 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000751 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000752 Failed example:
753 print x
754 Expected:
755 14
756 Got:
757 12
Edward Loperaacf0832004-08-26 01:19:50 +0000758 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000759 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000760 Expecting:
761 6
Tim Peters8485b562004-08-04 18:46:34 +0000762 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000763 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000764"""
765 def verbose_flag(): r"""
766The `verbose` flag makes the test runner generate more detailed
767output:
768
769 >>> def f(x):
770 ... '''
771 ... >>> x = 12
772 ... >>> print x
773 ... 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000774 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000775 ... 6
776 ... '''
777 >>> test = doctest.DocTestFinder().find(f)[0]
778
779 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000780 Trying:
781 x = 12
782 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000783 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000784 Trying:
785 print x
786 Expecting:
787 12
Tim Peters8485b562004-08-04 18:46:34 +0000788 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000789 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000790 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000791 Expecting:
792 6
Tim Peters8485b562004-08-04 18:46:34 +0000793 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000794 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000795
796If the `verbose` flag is unspecified, then the output will be verbose
797iff `-v` appears in sys.argv:
798
799 >>> # Save the real sys.argv list.
800 >>> old_argv = sys.argv
801
802 >>> # If -v does not appear in sys.argv, then output isn't verbose.
803 >>> sys.argv = ['test']
804 >>> doctest.DocTestRunner().run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000805 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000806
807 >>> # If -v does appear in sys.argv, then output is verbose.
808 >>> sys.argv = ['test', '-v']
809 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000810 Trying:
811 x = 12
812 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000813 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000814 Trying:
815 print x
816 Expecting:
817 12
Tim Peters8485b562004-08-04 18:46:34 +0000818 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000819 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000820 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000821 Expecting:
822 6
Tim Peters8485b562004-08-04 18:46:34 +0000823 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000824 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000825
826 >>> # Restore sys.argv
827 >>> sys.argv = old_argv
828
829In the remaining examples, the test runner's verbosity will be
830explicitly set, to ensure that the test behavior is consistent.
831 """
832 def exceptions(): r"""
833Tests of `DocTestRunner`'s exception handling.
834
835An expected exception is specified with a traceback message. The
836lines between the first line and the type/value may be omitted or
837replaced with any other string:
838
839 >>> def f(x):
840 ... '''
841 ... >>> x = 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000842 ... >>> print x//0
Tim Peters8485b562004-08-04 18:46:34 +0000843 ... Traceback (most recent call last):
844 ... ZeroDivisionError: integer division or modulo by zero
845 ... '''
846 >>> test = doctest.DocTestFinder().find(f)[0]
847 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000848 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000849
Edward Loper19b19582004-08-25 23:07:03 +0000850An example may not generate output before it raises an exception; if
851it does, then the traceback message will not be recognized as
852signaling an expected exception, so the example will be reported as an
853unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000854
855 >>> def f(x):
856 ... '''
857 ... >>> x = 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000858 ... >>> print 'pre-exception output', x//0
Tim Peters8485b562004-08-04 18:46:34 +0000859 ... pre-exception output
860 ... Traceback (most recent call last):
861 ... ZeroDivisionError: integer division or modulo by zero
862 ... '''
863 >>> test = doctest.DocTestFinder().find(f)[0]
864 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000865 ... # doctest: +ELLIPSIS
866 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000867 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000868 Failed example:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000869 print 'pre-exception output', x//0
Edward Loper19b19582004-08-25 23:07:03 +0000870 Exception raised:
871 ...
872 ZeroDivisionError: integer division or modulo by zero
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000873 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000874
875Exception messages may contain newlines:
876
877 >>> def f(x):
878 ... r'''
879 ... >>> raise ValueError, 'multi\nline\nmessage'
880 ... Traceback (most recent call last):
881 ... ValueError: multi
882 ... line
883 ... message
884 ... '''
885 >>> test = doctest.DocTestFinder().find(f)[0]
886 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000887 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000888
889If an exception is expected, but an exception with the wrong type or
890message is raised, then it is reported as a failure:
891
892 >>> def f(x):
893 ... r'''
894 ... >>> raise ValueError, 'message'
895 ... Traceback (most recent call last):
896 ... ValueError: wrong message
897 ... '''
898 >>> test = doctest.DocTestFinder().find(f)[0]
899 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000900 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000901 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000902 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000903 Failed example:
904 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000905 Expected:
906 Traceback (most recent call last):
907 ValueError: wrong message
908 Got:
909 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000910 ...
Tim Peters8485b562004-08-04 18:46:34 +0000911 ValueError: message
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000912 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000913
Tim Peters1fbf9c52004-09-04 17:21:02 +0000914However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
915detail:
916
917 >>> def f(x):
918 ... r'''
919 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
920 ... Traceback (most recent call last):
921 ... ValueError: wrong message
922 ... '''
923 >>> test = doctest.DocTestFinder().find(f)[0]
924 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000925 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000926
Nick Coghlandfb45df2010-04-28 14:29:06 +0000927IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
928between Python versions. For example, in Python 3.x, the module path of
929the exception is in the output, but this will fail under Python 2:
930
931 >>> def f(x):
932 ... r'''
933 ... >>> from httplib import HTTPException
934 ... >>> raise HTTPException('message')
935 ... Traceback (most recent call last):
936 ... httplib.HTTPException: message
937 ... '''
938 >>> test = doctest.DocTestFinder().find(f)[0]
939 >>> doctest.DocTestRunner(verbose=False).run(test)
940 ... # doctest: +ELLIPSIS
941 **********************************************************************
942 File ..., line 4, in f
943 Failed example:
944 raise HTTPException('message')
945 Expected:
946 Traceback (most recent call last):
947 httplib.HTTPException: message
948 Got:
949 Traceback (most recent call last):
950 ...
951 HTTPException: message
952 TestResults(failed=1, attempted=2)
953
954But in Python 2 the module path is not included, an therefore a test must look
955like the following test to succeed in Python 2. But that test will fail under
956Python 3.
957
958 >>> def f(x):
959 ... r'''
960 ... >>> from httplib import HTTPException
961 ... >>> raise HTTPException('message')
962 ... Traceback (most recent call last):
963 ... HTTPException: message
964 ... '''
965 >>> test = doctest.DocTestFinder().find(f)[0]
966 >>> doctest.DocTestRunner(verbose=False).run(test)
967 TestResults(failed=0, attempted=2)
968
969However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
970(if any) will be ignored:
971
972 >>> def f(x):
973 ... r'''
974 ... >>> from httplib import HTTPException
975 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
976 ... Traceback (most recent call last):
977 ... HTTPException: message
978 ... '''
979 >>> test = doctest.DocTestFinder().find(f)[0]
980 >>> doctest.DocTestRunner(verbose=False).run(test)
981 TestResults(failed=0, attempted=2)
982
983The module path will be completely ignored, so two different module paths will
984still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
985be used when exceptions have changed module.
986
987 >>> def f(x):
988 ... r'''
989 ... >>> from httplib import HTTPException
990 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
991 ... Traceback (most recent call last):
992 ... foo.bar.HTTPException: message
993 ... '''
994 >>> test = doctest.DocTestFinder().find(f)[0]
995 >>> doctest.DocTestRunner(verbose=False).run(test)
996 TestResults(failed=0, attempted=2)
997
Tim Peters1fbf9c52004-09-04 17:21:02 +0000998But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
999
1000 >>> def f(x):
1001 ... r'''
1002 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
1003 ... Traceback (most recent call last):
1004 ... TypeError: wrong type
1005 ... '''
1006 >>> test = doctest.DocTestFinder().find(f)[0]
1007 >>> doctest.DocTestRunner(verbose=False).run(test)
1008 ... # doctest: +ELLIPSIS
1009 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001010 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001011 Failed example:
1012 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
1013 Expected:
1014 Traceback (most recent call last):
1015 TypeError: wrong type
1016 Got:
1017 Traceback (most recent call last):
1018 ...
1019 ValueError: message
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001020 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001021
Tim Peters0ee9baa2013-12-03 21:02:05 -06001022If the exception does not have a message, you can still use
1023IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1024
1025 >>> def f(x):
1026 ... r'''
Tim Petersc289fa72013-12-03 21:49:30 -06001027 ... >>> from Queue import Empty
1028 ... >>> raise Empty() #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters0ee9baa2013-12-03 21:02:05 -06001029 ... Traceback (most recent call last):
Tim Petersc289fa72013-12-03 21:49:30 -06001030 ... foo.bar.Empty
Tim Peters0ee9baa2013-12-03 21:02:05 -06001031 ... '''
1032 >>> test = doctest.DocTestFinder().find(f)[0]
1033 >>> doctest.DocTestRunner(verbose=False).run(test)
1034 TestResults(failed=0, attempted=2)
1035
1036Note that a trailing colon doesn't matter either:
1037
1038 >>> def f(x):
1039 ... r'''
Tim Petersc289fa72013-12-03 21:49:30 -06001040 ... >>> from Queue import Empty
1041 ... >>> raise Empty() #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters0ee9baa2013-12-03 21:02:05 -06001042 ... Traceback (most recent call last):
Tim Petersc289fa72013-12-03 21:49:30 -06001043 ... foo.bar.Empty:
Tim Peters0ee9baa2013-12-03 21:02:05 -06001044 ... '''
1045 >>> test = doctest.DocTestFinder().find(f)[0]
1046 >>> doctest.DocTestRunner(verbose=False).run(test)
1047 TestResults(failed=0, attempted=2)
1048
Tim Peters8485b562004-08-04 18:46:34 +00001049If an exception is raised but not expected, then it is reported as an
1050unexpected exception:
1051
Tim Peters8485b562004-08-04 18:46:34 +00001052 >>> def f(x):
1053 ... r'''
Tim Peters1c5bc1c2006-03-28 07:28:40 +00001054 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001055 ... 0
1056 ... '''
1057 >>> test = doctest.DocTestFinder().find(f)[0]
1058 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001059 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001060 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001061 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001062 Failed example:
Tim Peters1c5bc1c2006-03-28 07:28:40 +00001063 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001064 Exception raised:
1065 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001066 ...
Tim Peters8485b562004-08-04 18:46:34 +00001067 ZeroDivisionError: integer division or modulo by zero
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001068 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001069"""
Georg Brandl50775992010-08-01 19:33:15 +00001070 def displayhook(): r"""
1071Test that changing sys.displayhook doesn't matter for doctest.
1072
1073 >>> import sys
1074 >>> orig_displayhook = sys.displayhook
1075 >>> def my_displayhook(x):
1076 ... print('hi!')
1077 >>> sys.displayhook = my_displayhook
1078 >>> def f():
1079 ... '''
1080 ... >>> 3
1081 ... 3
1082 ... '''
1083 >>> test = doctest.DocTestFinder().find(f)[0]
1084 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1085 >>> post_displayhook = sys.displayhook
1086
1087 We need to restore sys.displayhook now, so that we'll be able to test
1088 results.
1089
1090 >>> sys.displayhook = orig_displayhook
1091
1092 Ok, now we can check that everything is ok.
1093
1094 >>> r
1095 TestResults(failed=0, attempted=1)
1096 >>> post_displayhook is my_displayhook
1097 True
1098"""
Tim Peters8485b562004-08-04 18:46:34 +00001099 def optionflags(): r"""
1100Tests of `DocTestRunner`'s option flag handling.
1101
1102Several option flags can be used to customize the behavior of the test
1103runner. These are defined as module constants in doctest, and passed
Georg Brandlf725b952008-01-05 19:44:22 +00001104to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001105together).
1106
1107The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1108and 1/0:
1109
1110 >>> def f(x):
1111 ... '>>> True\n1\n'
1112
1113 >>> # Without the flag:
1114 >>> test = doctest.DocTestFinder().find(f)[0]
1115 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001116 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001117
1118 >>> # With the flag:
1119 >>> test = doctest.DocTestFinder().find(f)[0]
1120 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1121 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001122 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001123 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001124 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001125 Failed example:
1126 True
1127 Expected:
1128 1
1129 Got:
1130 True
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001131 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001132
1133The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1134and the '<BLANKLINE>' marker:
1135
1136 >>> def f(x):
1137 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
1138
1139 >>> # Without the flag:
1140 >>> test = doctest.DocTestFinder().find(f)[0]
1141 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001142 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001143
1144 >>> # With the flag:
1145 >>> test = doctest.DocTestFinder().find(f)[0]
1146 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1147 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001148 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001149 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001150 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001151 Failed example:
1152 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +00001153 Expected:
1154 a
1155 <BLANKLINE>
1156 b
1157 Got:
1158 a
1159 <BLANKLINE>
1160 b
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001161 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001162
1163The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1164treated as equal:
1165
1166 >>> def f(x):
1167 ... '>>> print 1, 2, 3\n 1 2\n 3'
1168
1169 >>> # Without the flag:
1170 >>> test = doctest.DocTestFinder().find(f)[0]
1171 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001172 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001173 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001174 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001175 Failed example:
1176 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +00001177 Expected:
1178 1 2
1179 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001180 Got:
1181 1 2 3
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001182 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001183
1184 >>> # With the flag:
1185 >>> test = doctest.DocTestFinder().find(f)[0]
1186 >>> flags = doctest.NORMALIZE_WHITESPACE
1187 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001188 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001189
Tim Peters026f8dc2004-08-19 16:38:58 +00001190 An example from the docs:
1191 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
1192 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1193 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1194
Tim Peters8485b562004-08-04 18:46:34 +00001195The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1196output to match any substring in the actual output:
1197
1198 >>> def f(x):
1199 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1200
1201 >>> # Without the flag:
1202 >>> test = doctest.DocTestFinder().find(f)[0]
1203 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001204 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001205 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001206 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001207 Failed example:
1208 print range(15)
1209 Expected:
1210 [0, 1, 2, ..., 14]
1211 Got:
1212 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001213 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001214
1215 >>> # With the flag:
1216 >>> test = doctest.DocTestFinder().find(f)[0]
1217 >>> flags = doctest.ELLIPSIS
1218 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001219 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001220
Tim Peterse594bee2004-08-22 01:47:51 +00001221 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001222
1223 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001224 ... print i**2, #doctest: +ELLIPSIS
1225 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001226
Tim Peters026f8dc2004-08-19 16:38:58 +00001227 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001228
1229 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001230 ... print i,
1231 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001232
Tim Peters026f8dc2004-08-19 16:38:58 +00001233 Examples from the docs:
1234
1235 >>> print range(20) # doctest:+ELLIPSIS
1236 [0, 1, ..., 18, 19]
1237
1238 >>> print range(20) # doctest: +ELLIPSIS
1239 ... # doctest: +NORMALIZE_WHITESPACE
1240 [0, 1, ..., 18, 19]
1241
Tim Peters711bf302006-04-25 03:31:36 +00001242The SKIP flag causes an example to be skipped entirely. I.e., the
1243example is not run. It can be useful in contexts where doctest
1244examples serve as both documentation and test cases, and an example
1245should be included for documentation purposes, but should not be
1246checked (e.g., because its output is random, or depends on resources
1247which would be unavailable.) The SKIP flag can also be used for
1248'commenting out' broken examples.
1249
1250 >>> import unavailable_resource # doctest: +SKIP
1251 >>> unavailable_resource.do_something() # doctest: +SKIP
1252 >>> unavailable_resource.blow_up() # doctest: +SKIP
1253 Traceback (most recent call last):
1254 ...
1255 UncheckedBlowUpError: Nobody checks me.
1256
1257 >>> import random
1258 >>> print random.random() # doctest: +SKIP
1259 0.721216923889
1260
Edward Loper71f55af2004-08-26 01:41:51 +00001261The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001262and actual outputs to be displayed using a unified diff:
1263
1264 >>> def f(x):
1265 ... r'''
1266 ... >>> print '\n'.join('abcdefg')
1267 ... a
1268 ... B
1269 ... c
1270 ... d
1271 ... f
1272 ... g
1273 ... h
1274 ... '''
1275
1276 >>> # Without the flag:
1277 >>> test = doctest.DocTestFinder().find(f)[0]
1278 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001279 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001280 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001281 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001282 Failed example:
1283 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001284 Expected:
1285 a
1286 B
1287 c
1288 d
1289 f
1290 g
1291 h
1292 Got:
1293 a
1294 b
1295 c
1296 d
1297 e
1298 f
1299 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001300 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001301
1302 >>> # With the flag:
1303 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001304 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001305 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001306 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001307 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001308 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001309 Failed example:
1310 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001311 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001312 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001313 a
1314 -B
1315 +b
1316 c
1317 d
1318 +e
1319 f
1320 g
1321 -h
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001322 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001323
Edward Loper71f55af2004-08-26 01:41:51 +00001324The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001325and actual outputs to be displayed using a context diff:
1326
Edward Loper71f55af2004-08-26 01:41:51 +00001327 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001328 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001329 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001330 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001331 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001332 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001333 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001334 Failed example:
1335 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001336 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001337 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001338 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001339 a
1340 ! B
1341 c
1342 d
1343 f
1344 g
1345 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001346 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001347 a
1348 ! b
1349 c
1350 d
1351 + e
1352 f
1353 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001354 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001355
1356
Edward Loper71f55af2004-08-26 01:41:51 +00001357The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001358used by the popular ndiff.py utility. This does intraline difference
1359marking, as well as interline differences.
1360
1361 >>> def f(x):
1362 ... r'''
1363 ... >>> print "a b c d e f g h i j k l m"
1364 ... a b c d e f g h i j k 1 m
1365 ... '''
1366 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001367 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001368 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001369 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001370 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001371 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001372 Failed example:
1373 print "a b c d e f g h i j k l m"
1374 Differences (ndiff with -expected +actual):
1375 - a b c d e f g h i j k 1 m
1376 ? ^
1377 + a b c d e f g h i j k l m
1378 ? + ++ ^
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001379 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001380
Ezio Melottic2077b02011-03-16 12:34:31 +02001381The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001382failing example:
1383
1384 >>> def f(x):
1385 ... r'''
1386 ... >>> print 1 # first success
1387 ... 1
1388 ... >>> print 2 # first failure
1389 ... 200
1390 ... >>> print 3 # second failure
1391 ... 300
1392 ... >>> print 4 # second success
1393 ... 4
1394 ... >>> print 5 # third failure
1395 ... 500
1396 ... '''
1397 >>> test = doctest.DocTestFinder().find(f)[0]
1398 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1399 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001400 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001401 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001402 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001403 Failed example:
1404 print 2 # first failure
1405 Expected:
1406 200
1407 Got:
1408 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001409 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001410
Ezio Melottic2077b02011-03-16 12:34:31 +02001411However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001412
1413 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001414 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001415 Trying:
1416 print 1 # first success
1417 Expecting:
1418 1
1419 ok
1420 Trying:
1421 print 2 # first failure
1422 Expecting:
1423 200
1424 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001425 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001426 Failed example:
1427 print 2 # first failure
1428 Expected:
1429 200
1430 Got:
1431 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001432 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001433
1434For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1435count as failures:
1436
1437 >>> def f(x):
1438 ... r'''
1439 ... >>> print 1 # first success
1440 ... 1
1441 ... >>> raise ValueError(2) # first failure
1442 ... 200
1443 ... >>> print 3 # second failure
1444 ... 300
1445 ... >>> print 4 # second success
1446 ... 4
1447 ... >>> print 5 # third failure
1448 ... 500
1449 ... '''
1450 >>> test = doctest.DocTestFinder().find(f)[0]
1451 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1452 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1453 ... # doctest: +ELLIPSIS
1454 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001455 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001456 Failed example:
1457 raise ValueError(2) # first failure
1458 Exception raised:
1459 ...
1460 ValueError: 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001461 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001462
Tim Petersad2ef332006-05-10 02:43:01 +00001463New option flags can also be registered, via register_optionflag(). Here
1464we reach into doctest's internals a bit.
1465
1466 >>> unlikely = "UNLIKELY_OPTION_NAME"
1467 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1468 False
1469 >>> new_flag_value = doctest.register_optionflag(unlikely)
1470 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1471 True
1472
1473Before 2.4.4/2.5, registering a name more than once erroneously created
1474more than one flag value. Here we verify that's fixed:
1475
1476 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1477 >>> redundant_flag_value == new_flag_value
1478 True
1479
1480Clean up.
1481 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1482
Tim Petersc6cbab02004-08-22 19:43:28 +00001483 """
1484
Tim Peters8485b562004-08-04 18:46:34 +00001485 def option_directives(): r"""
1486Tests of `DocTestRunner`'s option directive mechanism.
1487
Edward Loper74bca7a2004-08-12 02:27:44 +00001488Option directives can be used to turn option flags on or off for a
1489single example. To turn an option on for an example, follow that
1490example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001491
1492 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001493 ... >>> print range(10) # should fail: no ellipsis
1494 ... [0, 1, ..., 9]
1495 ...
1496 ... >>> print range(10) # doctest: +ELLIPSIS
1497 ... [0, 1, ..., 9]
1498 ... '''
1499 >>> test = doctest.DocTestFinder().find(f)[0]
1500 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001501 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001502 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001503 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001504 Failed example:
1505 print range(10) # should fail: no ellipsis
1506 Expected:
1507 [0, 1, ..., 9]
1508 Got:
1509 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001510 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001511
1512To turn an option off for an example, follow that example with a
1513comment of the form ``# doctest: -OPTION``:
1514
1515 >>> def f(x): r'''
1516 ... >>> print range(10)
1517 ... [0, 1, ..., 9]
1518 ...
1519 ... >>> # should fail: no ellipsis
1520 ... >>> print range(10) # doctest: -ELLIPSIS
1521 ... [0, 1, ..., 9]
1522 ... '''
1523 >>> test = doctest.DocTestFinder().find(f)[0]
1524 >>> doctest.DocTestRunner(verbose=False,
1525 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001526 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001527 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001528 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001529 Failed example:
1530 print range(10) # doctest: -ELLIPSIS
1531 Expected:
1532 [0, 1, ..., 9]
1533 Got:
1534 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001535 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001536
1537Option directives affect only the example that they appear with; they
1538do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001539
Edward Loper74bca7a2004-08-12 02:27:44 +00001540 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001541 ... >>> print range(10) # Should fail: no ellipsis
1542 ... [0, 1, ..., 9]
1543 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001544 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001545 ... [0, 1, ..., 9]
1546 ...
Tim Peters8485b562004-08-04 18:46:34 +00001547 ... >>> print range(10) # Should fail: no ellipsis
1548 ... [0, 1, ..., 9]
1549 ... '''
1550 >>> test = doctest.DocTestFinder().find(f)[0]
1551 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001552 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001553 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001554 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001555 Failed example:
1556 print range(10) # Should fail: no ellipsis
1557 Expected:
1558 [0, 1, ..., 9]
1559 Got:
1560 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001561 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001562 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001563 Failed example:
1564 print range(10) # Should fail: no ellipsis
1565 Expected:
1566 [0, 1, ..., 9]
1567 Got:
1568 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001569 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001570
Edward Loper74bca7a2004-08-12 02:27:44 +00001571Multiple options may be modified by a single option directive. They
1572may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001573
1574 >>> def f(x): r'''
1575 ... >>> print range(10) # Should fail
1576 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001577 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001578 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001579 ... [0, 1, ..., 9]
1580 ... '''
1581 >>> test = doctest.DocTestFinder().find(f)[0]
1582 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001583 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001584 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001585 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001586 Failed example:
1587 print range(10) # Should fail
1588 Expected:
1589 [0, 1, ..., 9]
1590 Got:
1591 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001592 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001593
1594 >>> def f(x): r'''
1595 ... >>> print range(10) # Should fail
1596 ... [0, 1, ..., 9]
1597 ... >>> print range(10) # Should succeed
1598 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1599 ... [0, 1, ..., 9]
1600 ... '''
1601 >>> test = doctest.DocTestFinder().find(f)[0]
1602 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001603 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001604 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001605 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001606 Failed example:
1607 print range(10) # Should fail
1608 Expected:
1609 [0, 1, ..., 9]
1610 Got:
1611 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001612 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001613
1614 >>> def f(x): r'''
1615 ... >>> print range(10) # Should fail
1616 ... [0, 1, ..., 9]
1617 ... >>> print range(10) # Should succeed
1618 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1619 ... [0, 1, ..., 9]
1620 ... '''
1621 >>> test = doctest.DocTestFinder().find(f)[0]
1622 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001623 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001624 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001625 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001626 Failed example:
1627 print range(10) # Should fail
1628 Expected:
1629 [0, 1, ..., 9]
1630 Got:
1631 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001632 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001633
1634The option directive may be put on the line following the source, as
1635long as a continuation prompt is used:
1636
1637 >>> def f(x): r'''
1638 ... >>> print range(10)
1639 ... ... # doctest: +ELLIPSIS
1640 ... [0, 1, ..., 9]
1641 ... '''
1642 >>> test = doctest.DocTestFinder().find(f)[0]
1643 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001644 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001645
Edward Loper74bca7a2004-08-12 02:27:44 +00001646For examples with multi-line source, the option directive may appear
1647at the end of any line:
1648
1649 >>> def f(x): r'''
1650 ... >>> for x in range(10): # doctest: +ELLIPSIS
1651 ... ... print x,
1652 ... 0 1 2 ... 9
1653 ...
1654 ... >>> for x in range(10):
1655 ... ... print x, # doctest: +ELLIPSIS
1656 ... 0 1 2 ... 9
1657 ... '''
1658 >>> test = doctest.DocTestFinder().find(f)[0]
1659 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001660 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001661
1662If more than one line of an example with multi-line source has an
1663option directive, then they are combined:
1664
1665 >>> def f(x): r'''
1666 ... Should fail (option directive not on the last line):
1667 ... >>> for x in range(10): # doctest: +ELLIPSIS
1668 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1669 ... 0 1 2...9
1670 ... '''
1671 >>> test = doctest.DocTestFinder().find(f)[0]
1672 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001673 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001674
1675It is an error to have a comment of the form ``# doctest:`` that is
1676*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1677``OPTION`` is an option that has been registered with
1678`register_option`:
1679
1680 >>> # Error: Option not registered
1681 >>> s = '>>> print 12 #doctest: +BADOPTION'
1682 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1683 Traceback (most recent call last):
1684 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1685
1686 >>> # Error: No + or - prefix
1687 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1688 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1689 Traceback (most recent call last):
1690 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1691
1692It is an error to use an option directive on a line that contains no
1693source:
1694
1695 >>> s = '>>> # doctest: +ELLIPSIS'
1696 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1697 Traceback (most recent call last):
1698 ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
Georg Brandl1f05e2e2010-08-01 08:22:05 +00001699
1700 """
1701
1702 def test_unicode_output(self): r"""
1703
1704Check that unicode output works:
1705
1706 >>> u'\xe9'
1707 u'\xe9'
1708
1709If we return unicode, SpoofOut's buf variable becomes automagically
1710converted to unicode. This means all subsequent output becomes converted
1711to unicode, and if the output contains non-ascii characters that failed.
1712It used to be that this state change carried on between tests, meaning
1713tests would fail if unicode has been output previously in the testrun.
1714This test tests that this is no longer so:
1715
1716 >>> print u'abc'
1717 abc
1718
1719And then return a string with non-ascii characters:
1720
1721 >>> print u'\xe9'.encode('utf-8')
1722 é
1723
1724 """
1725
Tim Peters8485b562004-08-04 18:46:34 +00001726
1727def test_testsource(): r"""
1728Unit tests for `testsource()`.
1729
1730The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001731test with that name in that module, and converts it to a script. The
1732example code is converted to regular Python code. The surrounding
1733words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001734
1735 >>> import test.test_doctest
1736 >>> name = 'test.test_doctest.sample_func'
1737 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001738 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001739 #
Tim Peters8485b562004-08-04 18:46:34 +00001740 print sample_func(22)
1741 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001742 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001743 #
Edward Lopera5db6002004-08-12 02:41:30 +00001744 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001745 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001746
1747 >>> name = 'test.test_doctest.SampleNewStyleClass'
1748 >>> print doctest.testsource(test.test_doctest, name)
1749 print '1\n2\n3'
1750 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001751 ## 1
1752 ## 2
1753 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001754 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001755
1756 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1757 >>> print doctest.testsource(test.test_doctest, name)
1758 print SampleClass.a_classmethod(10)
1759 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001760 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001761 print SampleClass(0).a_classmethod(10)
1762 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001763 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001764 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001765"""
1766
1767def test_debug(): r"""
1768
1769Create a docstring that we want to debug:
1770
1771 >>> s = '''
1772 ... >>> x = 12
1773 ... >>> print x
1774 ... 12
1775 ... '''
1776
1777Create some fake stdin input, to feed to the debugger:
1778
1779 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001780 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001781 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001782
1783Run the debugger on the docstring, and then restore sys.stdin.
1784
Edward Loper2de91ba2004-08-27 02:07:46 +00001785 >>> try: doctest.debug_src(s)
1786 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001787 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001788 (Pdb) next
1789 12
Tim Peters8485b562004-08-04 18:46:34 +00001790 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791 > <string>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001792 (Pdb) print x
1793 12
1794 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001795
1796"""
1797
Jim Fulton356fd192004-08-09 11:34:47 +00001798def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001799 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001800
Tim Peters413ced62004-08-09 15:43:47 +00001801 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001802 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001803 you use it. The doctest module changes sys.stdout so that it can
1804 capture program output. It also temporarily replaces pdb.set_trace
1805 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001806 see debugger output.
1807
1808 >>> doc = '''
1809 ... >>> x = 42
Florent Xicluna80800d32010-10-14 21:46:04 +00001810 ... >>> raise Exception('clé')
1811 ... Traceback (most recent call last):
1812 ... Exception: clé
Jim Fulton356fd192004-08-09 11:34:47 +00001813 ... >>> import pdb; pdb.set_trace()
1814 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001815 >>> parser = doctest.DocTestParser()
Florent Xiclunab67660f2010-10-14 21:10:45 +00001816 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001817 >>> runner = doctest.DocTestRunner(verbose=False)
1818
1819 To demonstrate this, we'll create a fake standard input that
1820 captures our debugger input:
1821
1822 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001823 >>> real_stdin = sys.stdin
1824 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001825 ... 'print x', # print data defined by the example
1826 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001827 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001828
Edward Loper2de91ba2004-08-27 02:07:46 +00001829 >>> try: runner.run(test)
1830 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001831 --Return--
Florent Xicluna80800d32010-10-14 21:46:04 +00001832 > <doctest foo-bär@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001833 -> import pdb; pdb.set_trace()
1834 (Pdb) print x
1835 42
1836 (Pdb) continue
Florent Xicluna80800d32010-10-14 21:46:04 +00001837 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001838
1839 You can also put pdb.set_trace in a function called from a test:
1840
1841 >>> def calls_set_trace():
1842 ... y=2
1843 ... import pdb; pdb.set_trace()
1844
1845 >>> doc = '''
1846 ... >>> x=1
1847 ... >>> calls_set_trace()
1848 ... '''
Florent Xiclunab67660f2010-10-14 21:10:45 +00001849 >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001850 >>> real_stdin = sys.stdin
1851 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001852 ... 'print y', # print data defined in the function
1853 ... 'up', # out of function
1854 ... 'print x', # print data defined by the example
1855 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001856 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001857
Tim Peters50c6bdb2004-11-08 22:07:37 +00001858 >>> try:
1859 ... runner.run(test)
1860 ... finally:
1861 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001862 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001863 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1864 -> import pdb; pdb.set_trace()
1865 (Pdb) print y
1866 2
1867 (Pdb) up
Florent Xiclunab67660f2010-10-14 21:10:45 +00001868 > <doctest foo-bär@baz[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001869 -> calls_set_trace()
1870 (Pdb) print x
1871 1
1872 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001873 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001874
1875 During interactive debugging, source code is shown, even for
1876 doctest examples:
1877
1878 >>> doc = '''
1879 ... >>> def f(x):
1880 ... ... g(x*2)
1881 ... >>> def g(x):
1882 ... ... print x+3
1883 ... ... import pdb; pdb.set_trace()
1884 ... >>> f(3)
1885 ... '''
Florent Xiclunab67660f2010-10-14 21:10:45 +00001886 >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001887 >>> real_stdin = sys.stdin
1888 >>> sys.stdin = _FakeInput([
1889 ... 'list', # list source from example 2
1890 ... 'next', # return from g()
1891 ... 'list', # list source from example 1
1892 ... 'next', # return from f()
1893 ... 'list', # list source from example 3
1894 ... 'continue', # stop debugging
1895 ... ''])
1896 >>> try: runner.run(test)
1897 ... finally: sys.stdin = real_stdin
1898 ... # doctest: +NORMALIZE_WHITESPACE
1899 --Return--
Florent Xiclunab67660f2010-10-14 21:10:45 +00001900 > <doctest foo-bär@baz[1]>(3)g()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001901 -> import pdb; pdb.set_trace()
1902 (Pdb) list
1903 1 def g(x):
1904 2 print x+3
1905 3 -> import pdb; pdb.set_trace()
1906 [EOF]
1907 (Pdb) next
1908 --Return--
Florent Xiclunab67660f2010-10-14 21:10:45 +00001909 > <doctest foo-bär@baz[0]>(2)f()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001910 -> g(x*2)
1911 (Pdb) list
1912 1 def f(x):
1913 2 -> g(x*2)
1914 [EOF]
1915 (Pdb) next
1916 --Return--
Florent Xiclunab67660f2010-10-14 21:10:45 +00001917 > <doctest foo-bär@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001918 -> f(3)
1919 (Pdb) list
1920 1 -> f(3)
1921 [EOF]
1922 (Pdb) continue
1923 **********************************************************************
Florent Xiclunab67660f2010-10-14 21:10:45 +00001924 File "foo-bär@baz.py", line 7, in foo-bär@baz
Edward Loper2de91ba2004-08-27 02:07:46 +00001925 Failed example:
1926 f(3)
1927 Expected nothing
1928 Got:
1929 9
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001930 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001931 """
1932
Tim Peters50c6bdb2004-11-08 22:07:37 +00001933def test_pdb_set_trace_nested():
1934 """This illustrates more-demanding use of set_trace with nested functions.
1935
1936 >>> class C(object):
1937 ... def calls_set_trace(self):
1938 ... y = 1
1939 ... import pdb; pdb.set_trace()
1940 ... self.f1()
1941 ... y = 2
1942 ... def f1(self):
1943 ... x = 1
1944 ... self.f2()
1945 ... x = 2
1946 ... def f2(self):
1947 ... z = 1
1948 ... z = 2
1949
1950 >>> calls_set_trace = C().calls_set_trace
1951
1952 >>> doc = '''
1953 ... >>> a = 1
1954 ... >>> calls_set_trace()
1955 ... '''
1956 >>> parser = doctest.DocTestParser()
1957 >>> runner = doctest.DocTestRunner(verbose=False)
Florent Xiclunab67660f2010-10-14 21:10:45 +00001958 >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001959 >>> real_stdin = sys.stdin
1960 >>> sys.stdin = _FakeInput([
1961 ... 'print y', # print data defined in the function
1962 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z',
1963 ... 'up', 'print x',
1964 ... 'up', 'print y',
1965 ... 'up', 'print foo',
1966 ... 'continue', # stop debugging
1967 ... ''])
1968
1969 >>> try:
1970 ... runner.run(test)
1971 ... finally:
1972 ... sys.stdin = real_stdin
1973 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1974 -> self.f1()
1975 (Pdb) print y
1976 1
1977 (Pdb) step
1978 --Call--
1979 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1980 -> def f1(self):
1981 (Pdb) step
1982 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1983 -> x = 1
1984 (Pdb) step
1985 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1986 -> self.f2()
1987 (Pdb) step
1988 --Call--
1989 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1990 -> def f2(self):
1991 (Pdb) step
1992 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1993 -> z = 1
1994 (Pdb) step
1995 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1996 -> z = 2
1997 (Pdb) print z
1998 1
1999 (Pdb) up
2000 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2001 -> self.f2()
2002 (Pdb) print x
2003 1
2004 (Pdb) up
2005 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2006 -> self.f1()
2007 (Pdb) print y
2008 1
2009 (Pdb) up
Florent Xiclunab67660f2010-10-14 21:10:45 +00002010 > <doctest foo-bär@baz[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00002011 -> calls_set_trace()
2012 (Pdb) print foo
2013 *** NameError: name 'foo' is not defined
2014 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002015 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00002016"""
2017
Tim Peters19397e52004-08-06 22:02:59 +00002018def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002019 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002020
2021 We create a Suite by providing a module. A module can be provided
2022 by passing a module object:
2023
2024 >>> import unittest
2025 >>> import test.sample_doctest
2026 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2027 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002028 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002029
2030 We can also supply the module by name:
2031
2032 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2033 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002034 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002035
R David Murray8d580532012-09-10 10:17:13 -04002036 The module need not contain any doctest examples:
2037
2038 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2039 >>> suite.run(unittest.TestResult())
2040 <unittest.result.TestResult run=0 errors=0 failures=0>
2041
2042 However, if DocTestSuite finds no docstrings, it raises an error:
2043
2044 >>> try:
2045 ... doctest.DocTestSuite('test.sample_doctest_no_docstrings')
2046 ... except ValueError as e:
2047 ... error = e
2048
2049 >>> print(error.args[1])
2050 has no docstrings
2051
2052 You can prevent this error by passing a DocTestFinder instance with
2053 the `exclude_empty` keyword argument set to False:
2054
2055 >>> finder = doctest.DocTestFinder(exclude_empty=False)
2056 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2057 ... test_finder=finder)
2058 >>> suite.run(unittest.TestResult())
2059 <unittest.result.TestResult run=0 errors=0 failures=0>
2060
Tim Peters19397e52004-08-06 22:02:59 +00002061 We can use the current module:
2062
2063 >>> suite = test.sample_doctest.test_suite()
2064 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002065 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002066
2067 We can supply global variables. If we pass globs, they will be
2068 used instead of the module globals. Here we'll pass an empty
2069 globals, triggering an extra error:
2070
2071 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2072 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002073 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002074
2075 Alternatively, we can provide extra globals. Here we'll make an
2076 error go away by providing an extra global variable:
2077
2078 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2079 ... extraglobs={'y': 1})
2080 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002081 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002082
2083 You can pass option flags. Here we'll cause an extra error
2084 by disabling the blank-line feature:
2085
2086 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002087 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002088 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002089 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002090
Tim Peters1e277ee2004-08-07 05:37:52 +00002091 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002092
Jim Fultonf54bad42004-08-28 14:57:56 +00002093 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002094 ... import test.test_doctest
2095 ... test.test_doctest.sillySetup = True
2096
Jim Fultonf54bad42004-08-28 14:57:56 +00002097 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002098 ... import test.test_doctest
2099 ... del test.test_doctest.sillySetup
2100
2101 Here, we installed a silly variable that the test expects:
2102
2103 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2104 ... setUp=setUp, tearDown=tearDown)
2105 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002106 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002107
2108 But the tearDown restores sanity:
2109
2110 >>> import test.test_doctest
2111 >>> test.test_doctest.sillySetup
2112 Traceback (most recent call last):
2113 ...
2114 AttributeError: 'module' object has no attribute 'sillySetup'
2115
Jim Fultonf54bad42004-08-28 14:57:56 +00002116 The setUp and tearDown funtions are passed test objects. Here
2117 we'll use the setUp function to supply the missing variable y:
2118
2119 >>> def setUp(test):
2120 ... test.globs['y'] = 1
2121
2122 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2123 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002124 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002125
2126 Here, we didn't need to use a tearDown function because we
2127 modified the test globals, which are a copy of the
2128 sample_doctest module dictionary. The test globals are
2129 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002130 """
2131
2132def test_DocFileSuite():
2133 """We can test tests found in text files using a DocFileSuite.
2134
2135 We create a suite by providing the names of one or more text
2136 files that include examples:
2137
2138 >>> import unittest
2139 >>> suite = doctest.DocFileSuite('test_doctest.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002140 ... 'test_doctest2.txt',
2141 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002142 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002143 <unittest.result.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002144
2145 The test files are looked for in the directory containing the
2146 calling module. A package keyword argument can be provided to
2147 specify a different relative location.
2148
2149 >>> import unittest
2150 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2151 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002152 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002153 ... package='test')
2154 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002155 <unittest.result.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002156
Brett Cannon43e53f82007-11-21 00:47:36 +00002157 Support for using a package's __loader__.get_data() is also
2158 provided.
2159
2160 >>> import unittest, pkgutil, test
Brett Cannoneaa2c982007-11-23 00:06:51 +00002161 >>> added_loader = False
Brett Cannon43e53f82007-11-21 00:47:36 +00002162 >>> if not hasattr(test, '__loader__'):
2163 ... test.__loader__ = pkgutil.get_loader(test)
2164 ... added_loader = True
2165 >>> try:
2166 ... suite = doctest.DocFileSuite('test_doctest.txt',
2167 ... 'test_doctest2.txt',
2168 ... 'test_doctest4.txt',
2169 ... package='test')
2170 ... suite.run(unittest.TestResult())
2171 ... finally:
Brett Cannon9db1d5a2007-11-21 00:58:03 +00002172 ... if added_loader:
2173 ... del test.__loader__
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002174 <unittest.result.TestResult run=3 errors=0 failures=3>
Brett Cannon43e53f82007-11-21 00:47:36 +00002175
Edward Loper0273f5b2004-09-18 20:27:04 +00002176 '/' should be used as a path separator. It will be converted
2177 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002178
2179 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2180 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002181 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002182
Edward Loper0273f5b2004-09-18 20:27:04 +00002183 If DocFileSuite is used from an interactive session, then files
2184 are resolved relative to the directory of sys.argv[0]:
2185
Christian Heimesc756d002007-11-27 21:34:01 +00002186 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002187 >>> save_argv = sys.argv
2188 >>> sys.argv = [test.test_doctest.__file__]
2189 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimesc756d002007-11-27 21:34:01 +00002190 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002191 >>> sys.argv = save_argv
2192
Edward Loper052d0cd2004-09-19 17:19:33 +00002193 By setting `module_relative=False`, os-specific paths may be
2194 used (including absolute paths and paths relative to the
2195 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002196
2197 >>> # Get the absolute path of the test package.
2198 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2199 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2200
2201 >>> # Use it to find the absolute path of test_doctest.txt.
2202 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2203
Edward Loper052d0cd2004-09-19 17:19:33 +00002204 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002205 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002206 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002207
Edward Loper052d0cd2004-09-19 17:19:33 +00002208 It is an error to specify `package` when `module_relative=False`:
2209
2210 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2211 ... package='test')
2212 Traceback (most recent call last):
2213 ValueError: Package may only be specified for module-relative paths.
2214
Tim Peters19397e52004-08-06 22:02:59 +00002215 You can specify initial global variables:
2216
2217 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2218 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002219 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002220 ... globs={'favorite_color': 'blue'})
2221 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002222 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002223
2224 In this case, we supplied a missing favorite color. You can
2225 provide doctest options:
2226
2227 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2228 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002229 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002230 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2231 ... globs={'favorite_color': 'blue'})
2232 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002233 <unittest.result.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002234
2235 And, you can provide setUp and tearDown functions:
2236
Jim Fultonf54bad42004-08-28 14:57:56 +00002237 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002238 ... import test.test_doctest
2239 ... test.test_doctest.sillySetup = True
2240
Jim Fultonf54bad42004-08-28 14:57:56 +00002241 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002242 ... import test.test_doctest
2243 ... del test.test_doctest.sillySetup
2244
2245 Here, we installed a silly variable that the test expects:
2246
2247 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2248 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002249 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002250 ... setUp=setUp, tearDown=tearDown)
2251 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002252 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002253
2254 But the tearDown restores sanity:
2255
2256 >>> import test.test_doctest
2257 >>> test.test_doctest.sillySetup
2258 Traceback (most recent call last):
2259 ...
2260 AttributeError: 'module' object has no attribute 'sillySetup'
2261
Jim Fultonf54bad42004-08-28 14:57:56 +00002262 The setUp and tearDown funtions are passed test objects.
2263 Here, we'll use a setUp function to set the favorite color in
2264 test_doctest.txt:
2265
2266 >>> def setUp(test):
2267 ... test.globs['favorite_color'] = 'blue'
2268
2269 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2270 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002271 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002272
2273 Here, we didn't need to use a tearDown function because we
2274 modified the test globals. The test globals are
2275 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002276
Fred Drake7c404a42004-12-21 23:46:34 +00002277 Tests in a file run using `DocFileSuite` can also access the
2278 `__file__` global, which is set to the name of the file
2279 containing the tests:
2280
2281 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2282 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002283 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002284
George Yoshidaf3c65de2006-05-28 16:39:09 +00002285 If the tests contain non-ASCII characters, we have to specify which
2286 encoding the file is encoded with. We do so by using the `encoding`
2287 parameter:
2288
2289 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2290 ... 'test_doctest2.txt',
2291 ... 'test_doctest4.txt',
2292 ... encoding='utf-8')
2293 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002294 <unittest.result.TestResult run=3 errors=0 failures=2>
George Yoshidaf3c65de2006-05-28 16:39:09 +00002295
Jim Fultonf54bad42004-08-28 14:57:56 +00002296 """
Tim Peters19397e52004-08-06 22:02:59 +00002297
Jim Fulton07a349c2004-08-22 14:10:00 +00002298def test_trailing_space_in_test():
2299 """
Tim Petersa7def722004-08-23 22:13:22 +00002300 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002301
Jim Fulton07a349c2004-08-22 14:10:00 +00002302 >>> x, y = 'foo', ''
2303 >>> print x, y
2304 foo \n
2305 """
Tim Peters19397e52004-08-06 22:02:59 +00002306
Jim Fultonf54bad42004-08-28 14:57:56 +00002307
2308def test_unittest_reportflags():
2309 """Default unittest reporting flags can be set to control reporting
2310
2311 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2312 only the first failure of each test. First, we'll look at the
2313 output without the flag. The file test_doctest.txt file has two
2314 tests. They both fail if blank lines are disabled:
2315
2316 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2317 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2318 >>> import unittest
2319 >>> result = suite.run(unittest.TestResult())
2320 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2321 Traceback ...
2322 Failed example:
2323 favorite_color
2324 ...
2325 Failed example:
2326 if 1:
2327 ...
2328
2329 Note that we see both failures displayed.
2330
2331 >>> old = doctest.set_unittest_reportflags(
2332 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2333
2334 Now, when we run the test:
2335
2336 >>> result = suite.run(unittest.TestResult())
2337 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2338 Traceback ...
2339 Failed example:
2340 favorite_color
2341 Exception raised:
2342 ...
2343 NameError: name 'favorite_color' is not defined
2344 <BLANKLINE>
2345 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002346
Jim Fultonf54bad42004-08-28 14:57:56 +00002347 We get only the first failure.
2348
2349 If we give any reporting options when we set up the tests,
2350 however:
2351
2352 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2353 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2354
2355 Then the default eporting options are ignored:
2356
2357 >>> result = suite.run(unittest.TestResult())
2358 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2359 Traceback ...
2360 Failed example:
2361 favorite_color
2362 ...
2363 Failed example:
2364 if 1:
2365 print 'a'
2366 print
2367 print 'b'
2368 Differences (ndiff with -expected +actual):
2369 a
2370 - <BLANKLINE>
2371 +
2372 b
2373 <BLANKLINE>
2374 <BLANKLINE>
2375
2376
2377 Test runners can restore the formatting flags after they run:
2378
2379 >>> ignored = doctest.set_unittest_reportflags(old)
2380
2381 """
2382
Edward Loper052d0cd2004-09-19 17:19:33 +00002383def test_testfile(): r"""
2384Tests for the `testfile()` function. This function runs all the
2385doctest examples in a given file. In its simple invokation, it is
2386called with the name of a file, which is taken to be relative to the
2387calling module. The return value is (#failures, #tests).
2388
Florent Xicluna2a903b22010-02-27 13:31:23 +00002389We don't want `-v` in sys.argv for these tests.
2390
2391 >>> save_argv = sys.argv
2392 >>> if '-v' in sys.argv:
2393 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2394
2395
Edward Loper052d0cd2004-09-19 17:19:33 +00002396 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2397 **********************************************************************
2398 File "...", line 6, in test_doctest.txt
2399 Failed example:
2400 favorite_color
2401 Exception raised:
2402 ...
2403 NameError: name 'favorite_color' is not defined
2404 **********************************************************************
2405 1 items had failures:
2406 1 of 2 in test_doctest.txt
2407 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002408 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002409 >>> doctest.master = None # Reset master.
2410
2411(Note: we'll be clearing doctest.master after each call to
Florent Xicluna07627882010-03-21 01:14:24 +00002412`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002413same name.)
2414
2415Globals may be specified with the `globs` and `extraglobs` parameters:
2416
2417 >>> globs = {'favorite_color': 'blue'}
2418 >>> doctest.testfile('test_doctest.txt', globs=globs)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002419 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002420 >>> doctest.master = None # Reset master.
2421
2422 >>> extraglobs = {'favorite_color': 'red'}
2423 >>> doctest.testfile('test_doctest.txt', globs=globs,
2424 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2425 **********************************************************************
2426 File "...", line 6, in test_doctest.txt
2427 Failed example:
2428 favorite_color
2429 Expected:
2430 'blue'
2431 Got:
2432 'red'
2433 **********************************************************************
2434 1 items had failures:
2435 1 of 2 in test_doctest.txt
2436 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002437 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002438 >>> doctest.master = None # Reset master.
2439
2440The file may be made relative to a given module or package, using the
2441optional `module_relative` parameter:
2442
2443 >>> doctest.testfile('test_doctest.txt', globs=globs,
2444 ... module_relative='test')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002445 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002446 >>> doctest.master = None # Reset master.
2447
Ezio Melottic2077b02011-03-16 12:34:31 +02002448Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002449
2450 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2451 Trying:
2452 favorite_color
2453 Expecting:
2454 'blue'
2455 ok
2456 Trying:
2457 if 1:
2458 print 'a'
2459 print
2460 print 'b'
2461 Expecting:
2462 a
2463 <BLANKLINE>
2464 b
2465 ok
2466 1 items passed all tests:
2467 2 tests in test_doctest.txt
2468 2 tests in 1 items.
2469 2 passed and 0 failed.
2470 Test passed.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002471 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002472 >>> doctest.master = None # Reset master.
2473
2474The name of the test may be specified with the optional `name`
2475parameter:
2476
2477 >>> doctest.testfile('test_doctest.txt', name='newname')
2478 ... # doctest: +ELLIPSIS
2479 **********************************************************************
2480 File "...", line 6, in newname
2481 ...
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002482 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002483 >>> doctest.master = None # Reset master.
2484
Ezio Melottic2077b02011-03-16 12:34:31 +02002485The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002486parameter:
2487
2488 >>> doctest.testfile('test_doctest.txt', report=False)
2489 ... # doctest: +ELLIPSIS
2490 **********************************************************************
2491 File "...", line 6, in test_doctest.txt
2492 Failed example:
2493 favorite_color
2494 Exception raised:
2495 ...
2496 NameError: name 'favorite_color' is not defined
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002497 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002498 >>> doctest.master = None # Reset master.
2499
2500The optional keyword argument `raise_on_error` can be used to raise an
2501exception on the first error (which may be useful for postmortem
2502debugging):
2503
2504 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2505 ... # doctest: +ELLIPSIS
2506 Traceback (most recent call last):
2507 UnexpectedException: ...
2508 >>> doctest.master = None # Reset master.
George Yoshidaf3c65de2006-05-28 16:39:09 +00002509
2510If the tests contain non-ASCII characters, the tests might fail, since
2511it's unknown which encoding is used. The encoding can be specified
2512using the optional keyword argument `encoding`:
2513
2514 >>> doctest.testfile('test_doctest4.txt') # doctest: +ELLIPSIS
2515 **********************************************************************
2516 File "...", line 7, in test_doctest4.txt
2517 Failed example:
2518 u'...'
2519 Expected:
2520 u'f\xf6\xf6'
2521 Got:
2522 u'f\xc3\xb6\xc3\xb6'
2523 **********************************************************************
2524 ...
2525 **********************************************************************
2526 1 items had failures:
2527 2 of 4 in test_doctest4.txt
2528 ***Test Failed*** 2 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002529 TestResults(failed=2, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002530 >>> doctest.master = None # Reset master.
2531
2532 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002533 TestResults(failed=0, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002534 >>> doctest.master = None # Reset master.
Florent Xicluna2a903b22010-02-27 13:31:23 +00002535
2536Switch the module encoding to 'utf-8' to test the verbose output without
2537bothering with the current sys.stdout encoding.
2538
2539 >>> doctest._encoding, saved_encoding = 'utf-8', doctest._encoding
2540 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2541 Trying:
2542 u'föö'
2543 Expecting:
2544 u'f\xf6\xf6'
2545 ok
2546 Trying:
2547 u'bÄ…r'
2548 Expecting:
2549 u'b\u0105r'
2550 ok
2551 Trying:
2552 'föö'
2553 Expecting:
2554 'f\xc3\xb6\xc3\xb6'
2555 ok
2556 Trying:
2557 'bÄ…r'
2558 Expecting:
2559 'b\xc4\x85r'
2560 ok
2561 1 items passed all tests:
2562 4 tests in test_doctest4.txt
2563 4 tests in 1 items.
2564 4 passed and 0 failed.
2565 Test passed.
2566 TestResults(failed=0, attempted=4)
2567 >>> doctest._encoding = saved_encoding
2568 >>> doctest.master = None # Reset master.
2569 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002570"""
2571
R David Murray9840db82014-10-02 21:53:50 -04002572def test_lineendings(): r"""
2573*nix systems use \n line endings, while Windows systems use \r\n. Python
2574handles this using universal newline mode for reading files. Let's make
2575sure doctest does so (issue 8473) by creating temporary test files using each
2576of the two line disciplines. One of the two will be the "wrong" one for the
2577platform the test is run on.
2578
2579Windows line endings first:
2580
2581 >>> import tempfile, os
2582 >>> fn = tempfile.mktemp()
2583 >>> open(fn, 'w').write('Test:\r\n\r\n >>> x = 1 + 1\r\n\r\nDone.\r\n')
2584 >>> doctest.testfile(fn, False)
2585 TestResults(failed=0, attempted=1)
2586 >>> os.remove(fn)
2587
2588And now *nix line endings:
2589
2590 >>> fn = tempfile.mktemp()
2591 >>> open(fn, 'w').write('Test:\n\n >>> x = 1 + 1\n\nDone.\n')
2592 >>> doctest.testfile(fn, False)
2593 TestResults(failed=0, attempted=1)
2594 >>> os.remove(fn)
2595
2596"""
2597
Tim Petersa7def722004-08-23 22:13:22 +00002598# old_test1, ... used to live in doctest.py, but cluttered it. Note
2599# that these use the deprecated doctest.Tester, so should go away (or
2600# be rewritten) someday.
2601
Tim Petersa7def722004-08-23 22:13:22 +00002602def old_test1(): r"""
2603>>> from doctest import Tester
2604>>> t = Tester(globs={'x': 42}, verbose=0)
2605>>> t.runstring(r'''
2606... >>> x = x * 2
2607... >>> print x
2608... 42
2609... ''', 'XYZ')
2610**********************************************************************
2611Line 3, in XYZ
2612Failed example:
2613 print x
2614Expected:
2615 42
2616Got:
2617 84
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002618TestResults(failed=1, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002619>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002620TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002621>>> t.summarize()
2622**********************************************************************
26231 items had failures:
2624 1 of 2 in XYZ
2625***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002626TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002627>>> t.summarize(verbose=1)
26281 items passed all tests:
2629 2 tests in example2
2630**********************************************************************
26311 items had failures:
2632 1 of 2 in XYZ
26334 tests in 2 items.
26343 passed and 1 failed.
2635***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002636TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002637"""
2638
2639def old_test2(): r"""
2640 >>> from doctest import Tester
2641 >>> t = Tester(globs={}, verbose=1)
2642 >>> test = r'''
2643 ... # just an example
2644 ... >>> x = 1 + 2
2645 ... >>> x
2646 ... 3
2647 ... '''
2648 >>> t.runstring(test, "Example")
2649 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002650 Trying:
2651 x = 1 + 2
2652 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002653 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002654 Trying:
2655 x
2656 Expecting:
2657 3
Tim Petersa7def722004-08-23 22:13:22 +00002658 ok
2659 0 of 2 examples failed in string Example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002660 TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002661"""
2662
2663def old_test3(): r"""
2664 >>> from doctest import Tester
2665 >>> t = Tester(globs={}, verbose=0)
2666 >>> def _f():
2667 ... '''Trivial docstring example.
2668 ... >>> assert 2 == 2
2669 ... '''
2670 ... return 32
2671 ...
2672 >>> t.rundoc(_f) # expect 0 failures in 1 example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002673 TestResults(failed=0, attempted=1)
Tim Petersa7def722004-08-23 22:13:22 +00002674"""
2675
2676def old_test4(): """
Christian Heimesc756d002007-11-27 21:34:01 +00002677 >>> import types
2678 >>> m1 = types.ModuleType('_m1')
2679 >>> m2 = types.ModuleType('_m2')
Tim Petersa7def722004-08-23 22:13:22 +00002680 >>> test_data = \"""
2681 ... def _f():
2682 ... '''>>> assert 1 == 1
2683 ... '''
2684 ... def g():
2685 ... '''>>> assert 2 != 1
2686 ... '''
2687 ... class H:
2688 ... '''>>> assert 2 > 1
2689 ... '''
2690 ... def bar(self):
2691 ... '''>>> assert 1 < 2
2692 ... '''
2693 ... \"""
2694 >>> exec test_data in m1.__dict__
2695 >>> exec test_data in m2.__dict__
2696 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2697
2698 Tests that objects outside m1 are excluded:
2699
2700 >>> from doctest import Tester
2701 >>> t = Tester(globs={}, verbose=0)
2702 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002703 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002704
2705 Once more, not excluding stuff outside m1:
2706
2707 >>> t = Tester(globs={}, verbose=0)
2708 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002709 TestResults(failed=0, attempted=8)
Tim Petersa7def722004-08-23 22:13:22 +00002710
2711 The exclusion of objects from outside the designated module is
2712 meant to be invoked automagically by testmod.
2713
2714 >>> doctest.testmod(m1, verbose=False)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002715 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002716"""
2717
Tim Peters8485b562004-08-04 18:46:34 +00002718######################################################################
2719## Main
2720######################################################################
2721
2722def test_main():
2723 # Check the doctest cases in doctest itself:
2724 test_support.run_doctest(doctest, verbosity=True)
Florent Xicluna07627882010-03-21 01:14:24 +00002725
Tim Peters8485b562004-08-04 18:46:34 +00002726 from test import test_doctest
Florent Xicluna6257a7b2010-03-31 22:01:03 +00002727
2728 # Ignore all warnings about the use of class Tester in this module.
Benjamin Petersonca01a762012-10-15 20:38:21 -04002729 deprecations = []
2730 if __debug__:
2731 deprecations.append(("class Tester is deprecated", DeprecationWarning))
Florent Xicluna6257a7b2010-03-31 22:01:03 +00002732 if sys.py3kwarning:
2733 deprecations += [("backquote not supported", SyntaxWarning),
2734 ("execfile.. not supported", DeprecationWarning)]
2735 with test_support.check_warnings(*deprecations):
Florent Xicluna07627882010-03-21 01:14:24 +00002736 # Check the doctest cases defined here:
2737 test_support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002738
Victor Stinneredb9f872010-04-27 21:51:26 +00002739import sys
Tim Peters8485b562004-08-04 18:46:34 +00002740def test_coverage(coverdir):
Victor Stinneredb9f872010-04-27 21:51:26 +00002741 trace = test_support.import_module('trace')
Tim Peters8485b562004-08-04 18:46:34 +00002742 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2743 trace=0, count=1)
2744 tracer.run('reload(doctest); test_main()')
2745 r = tracer.results()
2746 print 'Writing coverage results...'
2747 r.write_results(show_missing=True, summary=True,
2748 coverdir=coverdir)
2749
2750if __name__ == '__main__':
2751 if '-c' in sys.argv:
2752 test_coverage('/tmp/doctest.cover')
2753 else:
2754 test_main()