blob: 45ee96ec5f8df7174b833206b76605501d8114c3 [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'
Tim Peters8485b562004-08-04 18:46:34 +0000261"""
262
263def test_DocTest(): r"""
264Unit tests for the `DocTest` class.
265
266DocTest is a collection of examples, extracted from a docstring, along
267with information about where the docstring comes from (a name,
268filename, and line number). The docstring is parsed by the `DocTest`
269constructor:
270
271 >>> docstring = '''
272 ... >>> print 12
273 ... 12
274 ...
275 ... Non-example text.
276 ...
277 ... >>> print 'another\example'
278 ... another
279 ... example
280 ... '''
281 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000282 >>> parser = doctest.DocTestParser()
283 >>> test = parser.get_doctest(docstring, globs, 'some_test',
284 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000285 >>> print test
286 <DocTest some_test from some_file:20 (2 examples)>
287 >>> len(test.examples)
288 2
289 >>> e1, e2 = test.examples
290 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000291 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000292 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000293 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000294
295Source information (name, filename, and line number) is available as
296attributes on the doctest object:
297
298 >>> (test.name, test.filename, test.lineno)
299 ('some_test', 'some_file', 20)
300
301The line number of an example within its containing file is found by
302adding the line number of the example and the line number of its
303containing test:
304
305 >>> test.lineno + e1.lineno
306 21
307 >>> test.lineno + e2.lineno
308 26
309
310If the docstring contains inconsistant leading whitespace in the
311expected output of an example, then `DocTest` will raise a ValueError:
312
313 >>> docstring = r'''
314 ... >>> print 'bad\nindentation'
315 ... bad
316 ... indentation
317 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000318 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000319 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000320 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000321
322If the docstring contains inconsistent leading whitespace on
323continuation lines, then `DocTest` will raise a ValueError:
324
325 >>> docstring = r'''
326 ... >>> print ('bad indentation',
327 ... ... 2)
328 ... ('bad', 'indentation')
329 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000330 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000331 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000332 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
Tim Peters8485b562004-08-04 18:46:34 +0000333
334If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
335will raise a ValueError:
336
337 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000338 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000339 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000340 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
341
342If there's no blank space after a PS2 prompt ('...'), then `DocTest`
343will raise a ValueError:
344
345 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000346 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000347 Traceback (most recent call last):
348 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
349
Antoine Pitrou7a3d8ae2011-12-18 19:27:45 +0100350Compare `DocTest`:
351
352 >>> docstring = '''
353 ... >>> print 12
354 ... 12
355 ... '''
356 >>> test = parser.get_doctest(docstring, globs, 'some_test',
357 ... 'some_test', 20)
358 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
359 ... 'some_test', 20)
360 >>> test == same_test
361 True
362 >>> test != same_test
363 False
364 >>> docstring = '''
365 ... >>> print 42
366 ... 42
367 ... '''
368 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
369 ... 'other_file', 10)
370 >>> test == other_test
371 False
372 >>> test != other_test
373 True
374
375Compare `DocTestCase`:
376
377 >>> DocTestCase = doctest.DocTestCase
378 >>> test_case = DocTestCase(test)
379 >>> same_test_case = DocTestCase(same_test)
380 >>> other_test_case = DocTestCase(other_test)
381 >>> test_case == same_test_case
382 True
383 >>> test_case != same_test_case
384 False
385 >>> test == other_test_case
386 False
387 >>> test != other_test_case
388 True
389
Tim Peters8485b562004-08-04 18:46:34 +0000390"""
391
Tim Peters8485b562004-08-04 18:46:34 +0000392def test_DocTestFinder(): r"""
393Unit tests for the `DocTestFinder` class.
394
395DocTestFinder is used to extract DocTests from an object's docstring
396and the docstrings of its contained objects. It can be used with
397modules, functions, classes, methods, staticmethods, classmethods, and
398properties.
399
400Finding Tests in Functions
401~~~~~~~~~~~~~~~~~~~~~~~~~~
402For a function whose docstring contains examples, DocTestFinder.find()
403will return a single test (for that function's docstring):
404
Tim Peters8485b562004-08-04 18:46:34 +0000405 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000406
407We'll simulate a __file__ attr that ends in pyc:
408
409 >>> import test.test_doctest
410 >>> old = test.test_doctest.__file__
411 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
412
Tim Peters8485b562004-08-04 18:46:34 +0000413 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000414
Edward Loper74bca7a2004-08-12 02:27:44 +0000415 >>> print tests # doctest: +ELLIPSIS
Florent Xicluna2a903b22010-02-27 13:31:23 +0000416 [<DocTest sample_func from ...:17 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000417
Tim Peters4de7c5c2004-08-23 22:38:05 +0000418The exact name depends on how test_doctest was invoked, so allow for
419leading path components.
420
421 >>> tests[0].filename # doctest: +ELLIPSIS
422 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000423
424 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000425
Jim Fulton07a349c2004-08-22 14:10:00 +0000426
Tim Peters8485b562004-08-04 18:46:34 +0000427 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000428 >>> (e.source, e.want, e.lineno)
429 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000430
Edward Loper32ddbf72004-09-13 05:47:24 +0000431By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000432
433 >>> def no_docstring(v):
434 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000435 >>> finder.find(no_docstring)
436 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000437
438However, the optional argument `exclude_empty` to the DocTestFinder
439constructor can be used to exclude tests for objects with empty
440docstrings:
441
442 >>> def no_docstring(v):
443 ... pass
444 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
445 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000446 []
447
448If the function has a docstring with no examples, then a test with no
449examples is returned. (This lets `DocTestRunner` collect statistics
450about which functions have no tests -- but is that useful? And should
451an empty test also be created when there's no docstring?)
452
453 >>> def no_examples(v):
454 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000455 >>> finder.find(no_examples) # doctest: +ELLIPSIS
456 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000457
458Finding Tests in Classes
459~~~~~~~~~~~~~~~~~~~~~~~~
460For a class, DocTestFinder will create a test for the class's
461docstring, and will recursively explore its contents, including
462methods, classmethods, staticmethods, properties, and nested classes.
463
464 >>> finder = doctest.DocTestFinder()
465 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000466 >>> for t in tests:
467 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000468 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000469 3 SampleClass.NestedClass
470 1 SampleClass.NestedClass.__init__
471 1 SampleClass.__init__
472 2 SampleClass.a_classmethod
473 1 SampleClass.a_property
474 1 SampleClass.a_staticmethod
475 1 SampleClass.double
476 1 SampleClass.get
477
478New-style classes are also supported:
479
480 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000481 >>> for t in tests:
482 ... print '%2s %s' % (len(t.examples), t.name)
483 1 SampleNewStyleClass
484 1 SampleNewStyleClass.__init__
485 1 SampleNewStyleClass.double
486 1 SampleNewStyleClass.get
487
488Finding Tests in Modules
489~~~~~~~~~~~~~~~~~~~~~~~~
490For a module, DocTestFinder will create a test for the class's
491docstring, and will recursively explore its contents, including
492functions, classes, and the `__test__` dictionary, if it exists:
493
494 >>> # A module
Christian Heimesc756d002007-11-27 21:34:01 +0000495 >>> import types
496 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000497 >>> def triple(val):
498 ... '''
Edward Loper4ae900f2004-09-21 03:20:34 +0000499 ... >>> print triple(11)
Tim Peters8485b562004-08-04 18:46:34 +0000500 ... 33
501 ... '''
502 ... return val*3
503 >>> m.__dict__.update({
504 ... 'sample_func': sample_func,
505 ... 'SampleClass': SampleClass,
506 ... '__doc__': '''
507 ... Module docstring.
508 ... >>> print 'module'
509 ... module
510 ... ''',
511 ... '__test__': {
512 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
513 ... 'c': triple}})
514
515 >>> finder = doctest.DocTestFinder()
516 >>> # Use module=test.test_doctest, to prevent doctest from
517 >>> # ignoring the objects since they weren't defined in m.
518 >>> import test.test_doctest
519 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000520 >>> for t in tests:
521 ... print '%2s %s' % (len(t.examples), t.name)
522 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000523 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000524 3 some_module.SampleClass.NestedClass
525 1 some_module.SampleClass.NestedClass.__init__
526 1 some_module.SampleClass.__init__
527 2 some_module.SampleClass.a_classmethod
528 1 some_module.SampleClass.a_property
529 1 some_module.SampleClass.a_staticmethod
530 1 some_module.SampleClass.double
531 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000532 1 some_module.__test__.c
533 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000534 1 some_module.sample_func
535
536Duplicate Removal
537~~~~~~~~~~~~~~~~~
538If a single object is listed twice (under different names), then tests
539will only be generated for it once:
540
Tim Petersf3f57472004-08-08 06:11:48 +0000541 >>> from test import doctest_aliases
Amaury Forgeot d'Arcf81ff982009-06-14 21:20:40 +0000542 >>> assert doctest_aliases.TwoNames.f
543 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000544 >>> tests = excl_empty_finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000545 >>> print len(tests)
546 2
547 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000548 test.doctest_aliases.TwoNames
549
550 TwoNames.f and TwoNames.g are bound to the same object.
551 We can't guess which will be found in doctest's traversal of
552 TwoNames.__dict__ first, so we have to allow for either.
553
554 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000555 True
556
Tim Petersbf0400a2006-06-05 01:43:03 +0000557Empty Tests
558~~~~~~~~~~~
559By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000560
Tim Petersbf0400a2006-06-05 01:43:03 +0000561 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000562 >>> for t in tests:
563 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000564 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000565 3 SampleClass.NestedClass
566 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000567 1 SampleClass.__init__
Tim Petersbf0400a2006-06-05 01:43:03 +0000568 2 SampleClass.a_classmethod
569 1 SampleClass.a_property
570 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000571 1 SampleClass.double
572 1 SampleClass.get
573
574By default, that excluded objects with no doctests. exclude_empty=False
575tells it to include (empty) tests for objects with no doctests. This feature
576is really to support backward compatibility in what doctest.master.summarize()
577displays.
578
Tim Petersbf0400a2006-06-05 01:43:03 +0000579 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000580 >>> for t in tests:
581 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000582 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000583 3 SampleClass.NestedClass
584 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000585 0 SampleClass.NestedClass.get
586 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000587 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000588 2 SampleClass.a_classmethod
589 1 SampleClass.a_property
590 1 SampleClass.a_staticmethod
591 1 SampleClass.double
592 1 SampleClass.get
593
Tim Peters8485b562004-08-04 18:46:34 +0000594Turning off Recursion
595~~~~~~~~~~~~~~~~~~~~~
596DocTestFinder can be told not to look for tests in contained objects
597using the `recurse` flag:
598
599 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000600 >>> for t in tests:
601 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000602 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000603
604Line numbers
605~~~~~~~~~~~~
606DocTestFinder finds the line number of each example:
607
608 >>> def f(x):
609 ... '''
610 ... >>> x = 12
611 ...
612 ... some text
613 ...
614 ... >>> # examples are not created for comments & bare prompts.
615 ... >>>
616 ... ...
617 ...
618 ... >>> for x in range(10):
619 ... ... print x,
620 ... 0 1 2 3 4 5 6 7 8 9
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000621 ... >>> x//2
Edward Loperb51b2342004-08-17 16:37:12 +0000622 ... 6
623 ... '''
624 >>> test = doctest.DocTestFinder().find(f)[0]
625 >>> [e.lineno for e in test.examples]
626 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000627"""
628
Edward Loper00f8da72004-08-26 18:05:07 +0000629def test_DocTestParser(): r"""
630Unit tests for the `DocTestParser` class.
631
632DocTestParser is used to parse docstrings containing doctest examples.
633
634The `parse` method divides a docstring into examples and intervening
635text:
636
637 >>> s = '''
638 ... >>> x, y = 2, 3 # no output expected
639 ... >>> if 1:
640 ... ... print x
641 ... ... print y
642 ... 2
643 ... 3
644 ...
645 ... Some text.
646 ... >>> x+y
647 ... 5
648 ... '''
649 >>> parser = doctest.DocTestParser()
650 >>> for piece in parser.parse(s):
651 ... if isinstance(piece, doctest.Example):
652 ... print 'Example:', (piece.source, piece.want, piece.lineno)
653 ... else:
654 ... print ' Text:', `piece`
655 Text: '\n'
656 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
657 Text: ''
658 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
659 Text: '\nSome text.\n'
660 Example: ('x+y\n', '5\n', 9)
661 Text: ''
662
663The `get_examples` method returns just the examples:
664
665 >>> for piece in parser.get_examples(s):
666 ... print (piece.source, piece.want, piece.lineno)
667 ('x, y = 2, 3 # no output expected\n', '', 1)
668 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
669 ('x+y\n', '5\n', 9)
670
671The `get_doctest` method creates a Test from the examples, along with the
672given arguments:
673
674 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
675 >>> (test.name, test.filename, test.lineno)
676 ('name', 'filename', 5)
677 >>> for piece in test.examples:
678 ... print (piece.source, piece.want, piece.lineno)
679 ('x, y = 2, 3 # no output expected\n', '', 1)
680 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
681 ('x+y\n', '5\n', 9)
682"""
683
Tim Peters8485b562004-08-04 18:46:34 +0000684class test_DocTestRunner:
685 def basics(): r"""
686Unit tests for the `DocTestRunner` class.
687
688DocTestRunner is used to run DocTest test cases, and to accumulate
689statistics. Here's a simple DocTest case we can use:
690
691 >>> def f(x):
692 ... '''
693 ... >>> x = 12
694 ... >>> print x
695 ... 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000696 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000697 ... 6
698 ... '''
699 >>> test = doctest.DocTestFinder().find(f)[0]
700
701The main DocTestRunner interface is the `run` method, which runs a
702given DocTest case in a given namespace (globs). It returns a tuple
703`(f,t)`, where `f` is the number of failed tests and `t` is the number
704of tried tests.
705
706 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000707 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000708
709If any example produces incorrect output, then the test runner reports
710the failure and proceeds to the next example:
711
712 >>> def f(x):
713 ... '''
714 ... >>> x = 12
715 ... >>> print x
716 ... 14
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000717 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000718 ... 6
719 ... '''
720 >>> test = doctest.DocTestFinder().find(f)[0]
721 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000722 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000723 Trying:
724 x = 12
725 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000726 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000727 Trying:
728 print x
729 Expecting:
730 14
Tim Peters8485b562004-08-04 18:46:34 +0000731 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000732 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000733 Failed example:
734 print x
735 Expected:
736 14
737 Got:
738 12
Edward Loperaacf0832004-08-26 01:19:50 +0000739 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000740 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000741 Expecting:
742 6
Tim Peters8485b562004-08-04 18:46:34 +0000743 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000744 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000745"""
746 def verbose_flag(): r"""
747The `verbose` flag makes the test runner generate more detailed
748output:
749
750 >>> def f(x):
751 ... '''
752 ... >>> x = 12
753 ... >>> print x
754 ... 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000755 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000756 ... 6
757 ... '''
758 >>> test = doctest.DocTestFinder().find(f)[0]
759
760 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000761 Trying:
762 x = 12
763 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000764 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000765 Trying:
766 print x
767 Expecting:
768 12
Tim Peters8485b562004-08-04 18:46:34 +0000769 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000770 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000771 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000772 Expecting:
773 6
Tim Peters8485b562004-08-04 18:46:34 +0000774 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000775 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000776
777If the `verbose` flag is unspecified, then the output will be verbose
778iff `-v` appears in sys.argv:
779
780 >>> # Save the real sys.argv list.
781 >>> old_argv = sys.argv
782
783 >>> # If -v does not appear in sys.argv, then output isn't verbose.
784 >>> sys.argv = ['test']
785 >>> doctest.DocTestRunner().run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000786 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000787
788 >>> # If -v does appear in sys.argv, then output is verbose.
789 >>> sys.argv = ['test', '-v']
790 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000791 Trying:
792 x = 12
793 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000794 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000795 Trying:
796 print x
797 Expecting:
798 12
Tim Peters8485b562004-08-04 18:46:34 +0000799 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000800 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000801 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000802 Expecting:
803 6
Tim Peters8485b562004-08-04 18:46:34 +0000804 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000805 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000806
807 >>> # Restore sys.argv
808 >>> sys.argv = old_argv
809
810In the remaining examples, the test runner's verbosity will be
811explicitly set, to ensure that the test behavior is consistent.
812 """
813 def exceptions(): r"""
814Tests of `DocTestRunner`'s exception handling.
815
816An expected exception is specified with a traceback message. The
817lines between the first line and the type/value may be omitted or
818replaced with any other string:
819
820 >>> def f(x):
821 ... '''
822 ... >>> x = 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000823 ... >>> print x//0
Tim Peters8485b562004-08-04 18:46:34 +0000824 ... Traceback (most recent call last):
825 ... ZeroDivisionError: integer division or modulo by zero
826 ... '''
827 >>> test = doctest.DocTestFinder().find(f)[0]
828 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000829 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000830
Edward Loper19b19582004-08-25 23:07:03 +0000831An example may not generate output before it raises an exception; if
832it does, then the traceback message will not be recognized as
833signaling an expected exception, so the example will be reported as an
834unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000835
836 >>> def f(x):
837 ... '''
838 ... >>> x = 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000839 ... >>> print 'pre-exception output', x//0
Tim Peters8485b562004-08-04 18:46:34 +0000840 ... pre-exception output
841 ... Traceback (most recent call last):
842 ... ZeroDivisionError: integer division or modulo by zero
843 ... '''
844 >>> test = doctest.DocTestFinder().find(f)[0]
845 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000846 ... # doctest: +ELLIPSIS
847 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000848 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000849 Failed example:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000850 print 'pre-exception output', x//0
Edward Loper19b19582004-08-25 23:07:03 +0000851 Exception raised:
852 ...
853 ZeroDivisionError: integer division or modulo by zero
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000854 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000855
856Exception messages may contain newlines:
857
858 >>> def f(x):
859 ... r'''
860 ... >>> raise ValueError, 'multi\nline\nmessage'
861 ... Traceback (most recent call last):
862 ... ValueError: multi
863 ... line
864 ... message
865 ... '''
866 >>> test = doctest.DocTestFinder().find(f)[0]
867 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000868 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000869
870If an exception is expected, but an exception with the wrong type or
871message is raised, then it is reported as a failure:
872
873 >>> def f(x):
874 ... r'''
875 ... >>> raise ValueError, 'message'
876 ... Traceback (most recent call last):
877 ... ValueError: wrong message
878 ... '''
879 >>> test = doctest.DocTestFinder().find(f)[0]
880 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000881 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000882 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000883 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000884 Failed example:
885 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000886 Expected:
887 Traceback (most recent call last):
888 ValueError: wrong message
889 Got:
890 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000891 ...
Tim Peters8485b562004-08-04 18:46:34 +0000892 ValueError: message
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000893 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000894
Tim Peters1fbf9c52004-09-04 17:21:02 +0000895However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
896detail:
897
898 >>> def f(x):
899 ... r'''
900 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
901 ... Traceback (most recent call last):
902 ... ValueError: wrong message
903 ... '''
904 >>> test = doctest.DocTestFinder().find(f)[0]
905 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000906 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000907
Nick Coghlandfb45df2010-04-28 14:29:06 +0000908IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
909between Python versions. For example, in Python 3.x, the module path of
910the exception is in the output, but this will fail under Python 2:
911
912 >>> def f(x):
913 ... r'''
914 ... >>> from httplib import HTTPException
915 ... >>> raise HTTPException('message')
916 ... Traceback (most recent call last):
917 ... httplib.HTTPException: message
918 ... '''
919 >>> test = doctest.DocTestFinder().find(f)[0]
920 >>> doctest.DocTestRunner(verbose=False).run(test)
921 ... # doctest: +ELLIPSIS
922 **********************************************************************
923 File ..., line 4, in f
924 Failed example:
925 raise HTTPException('message')
926 Expected:
927 Traceback (most recent call last):
928 httplib.HTTPException: message
929 Got:
930 Traceback (most recent call last):
931 ...
932 HTTPException: message
933 TestResults(failed=1, attempted=2)
934
935But in Python 2 the module path is not included, an therefore a test must look
936like the following test to succeed in Python 2. But that test will fail under
937Python 3.
938
939 >>> def f(x):
940 ... r'''
941 ... >>> from httplib import HTTPException
942 ... >>> raise HTTPException('message')
943 ... Traceback (most recent call last):
944 ... HTTPException: message
945 ... '''
946 >>> test = doctest.DocTestFinder().find(f)[0]
947 >>> doctest.DocTestRunner(verbose=False).run(test)
948 TestResults(failed=0, attempted=2)
949
950However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
951(if any) will be ignored:
952
953 >>> def f(x):
954 ... r'''
955 ... >>> from httplib import HTTPException
956 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
957 ... Traceback (most recent call last):
958 ... HTTPException: message
959 ... '''
960 >>> test = doctest.DocTestFinder().find(f)[0]
961 >>> doctest.DocTestRunner(verbose=False).run(test)
962 TestResults(failed=0, attempted=2)
963
964The module path will be completely ignored, so two different module paths will
965still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
966be used when exceptions have changed module.
967
968 >>> def f(x):
969 ... r'''
970 ... >>> from httplib import HTTPException
971 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
972 ... Traceback (most recent call last):
973 ... foo.bar.HTTPException: message
974 ... '''
975 >>> test = doctest.DocTestFinder().find(f)[0]
976 >>> doctest.DocTestRunner(verbose=False).run(test)
977 TestResults(failed=0, attempted=2)
978
Tim Peters1fbf9c52004-09-04 17:21:02 +0000979But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
980
981 >>> def f(x):
982 ... r'''
983 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
984 ... Traceback (most recent call last):
985 ... TypeError: wrong type
986 ... '''
987 >>> test = doctest.DocTestFinder().find(f)[0]
988 >>> doctest.DocTestRunner(verbose=False).run(test)
989 ... # doctest: +ELLIPSIS
990 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000991 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000992 Failed example:
993 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
994 Expected:
995 Traceback (most recent call last):
996 TypeError: wrong type
997 Got:
998 Traceback (most recent call last):
999 ...
1000 ValueError: message
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001001 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001002
Tim Peters8485b562004-08-04 18:46:34 +00001003If an exception is raised but not expected, then it is reported as an
1004unexpected exception:
1005
Tim Peters8485b562004-08-04 18:46:34 +00001006 >>> def f(x):
1007 ... r'''
Tim Peters1c5bc1c2006-03-28 07:28:40 +00001008 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001009 ... 0
1010 ... '''
1011 >>> test = doctest.DocTestFinder().find(f)[0]
1012 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001013 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001014 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001015 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001016 Failed example:
Tim Peters1c5bc1c2006-03-28 07:28:40 +00001017 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001018 Exception raised:
1019 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001020 ...
Tim Peters8485b562004-08-04 18:46:34 +00001021 ZeroDivisionError: integer division or modulo by zero
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001022 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001023"""
Georg Brandl50775992010-08-01 19:33:15 +00001024 def displayhook(): r"""
1025Test that changing sys.displayhook doesn't matter for doctest.
1026
1027 >>> import sys
1028 >>> orig_displayhook = sys.displayhook
1029 >>> def my_displayhook(x):
1030 ... print('hi!')
1031 >>> sys.displayhook = my_displayhook
1032 >>> def f():
1033 ... '''
1034 ... >>> 3
1035 ... 3
1036 ... '''
1037 >>> test = doctest.DocTestFinder().find(f)[0]
1038 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1039 >>> post_displayhook = sys.displayhook
1040
1041 We need to restore sys.displayhook now, so that we'll be able to test
1042 results.
1043
1044 >>> sys.displayhook = orig_displayhook
1045
1046 Ok, now we can check that everything is ok.
1047
1048 >>> r
1049 TestResults(failed=0, attempted=1)
1050 >>> post_displayhook is my_displayhook
1051 True
1052"""
Tim Peters8485b562004-08-04 18:46:34 +00001053 def optionflags(): r"""
1054Tests of `DocTestRunner`'s option flag handling.
1055
1056Several option flags can be used to customize the behavior of the test
1057runner. These are defined as module constants in doctest, and passed
Georg Brandlf725b952008-01-05 19:44:22 +00001058to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001059together).
1060
1061The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1062and 1/0:
1063
1064 >>> def f(x):
1065 ... '>>> True\n1\n'
1066
1067 >>> # Without the flag:
1068 >>> test = doctest.DocTestFinder().find(f)[0]
1069 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001070 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001071
1072 >>> # With the flag:
1073 >>> test = doctest.DocTestFinder().find(f)[0]
1074 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1075 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001076 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001077 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001078 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001079 Failed example:
1080 True
1081 Expected:
1082 1
1083 Got:
1084 True
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001085 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001086
1087The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1088and the '<BLANKLINE>' marker:
1089
1090 >>> def f(x):
1091 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
1092
1093 >>> # Without the flag:
1094 >>> test = doctest.DocTestFinder().find(f)[0]
1095 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001096 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001097
1098 >>> # With the flag:
1099 >>> test = doctest.DocTestFinder().find(f)[0]
1100 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1101 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001102 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001103 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001104 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001105 Failed example:
1106 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +00001107 Expected:
1108 a
1109 <BLANKLINE>
1110 b
1111 Got:
1112 a
1113 <BLANKLINE>
1114 b
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001115 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001116
1117The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1118treated as equal:
1119
1120 >>> def f(x):
1121 ... '>>> print 1, 2, 3\n 1 2\n 3'
1122
1123 >>> # Without the flag:
1124 >>> test = doctest.DocTestFinder().find(f)[0]
1125 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001126 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001127 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001128 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001129 Failed example:
1130 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +00001131 Expected:
1132 1 2
1133 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001134 Got:
1135 1 2 3
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001136 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001137
1138 >>> # With the flag:
1139 >>> test = doctest.DocTestFinder().find(f)[0]
1140 >>> flags = doctest.NORMALIZE_WHITESPACE
1141 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001142 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001143
Tim Peters026f8dc2004-08-19 16:38:58 +00001144 An example from the docs:
1145 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
1146 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1147 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1148
Tim Peters8485b562004-08-04 18:46:34 +00001149The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1150output to match any substring in the actual output:
1151
1152 >>> def f(x):
1153 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1154
1155 >>> # Without the flag:
1156 >>> test = doctest.DocTestFinder().find(f)[0]
1157 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001158 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001159 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001160 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001161 Failed example:
1162 print range(15)
1163 Expected:
1164 [0, 1, 2, ..., 14]
1165 Got:
1166 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001167 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001168
1169 >>> # With the flag:
1170 >>> test = doctest.DocTestFinder().find(f)[0]
1171 >>> flags = doctest.ELLIPSIS
1172 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001173 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001174
Tim Peterse594bee2004-08-22 01:47:51 +00001175 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001176
1177 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001178 ... print i**2, #doctest: +ELLIPSIS
1179 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001180
Tim Peters026f8dc2004-08-19 16:38:58 +00001181 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001182
1183 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001184 ... print i,
1185 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001186
Tim Peters026f8dc2004-08-19 16:38:58 +00001187 Examples from the docs:
1188
1189 >>> print range(20) # doctest:+ELLIPSIS
1190 [0, 1, ..., 18, 19]
1191
1192 >>> print range(20) # doctest: +ELLIPSIS
1193 ... # doctest: +NORMALIZE_WHITESPACE
1194 [0, 1, ..., 18, 19]
1195
Tim Peters711bf302006-04-25 03:31:36 +00001196The SKIP flag causes an example to be skipped entirely. I.e., the
1197example is not run. It can be useful in contexts where doctest
1198examples serve as both documentation and test cases, and an example
1199should be included for documentation purposes, but should not be
1200checked (e.g., because its output is random, or depends on resources
1201which would be unavailable.) The SKIP flag can also be used for
1202'commenting out' broken examples.
1203
1204 >>> import unavailable_resource # doctest: +SKIP
1205 >>> unavailable_resource.do_something() # doctest: +SKIP
1206 >>> unavailable_resource.blow_up() # doctest: +SKIP
1207 Traceback (most recent call last):
1208 ...
1209 UncheckedBlowUpError: Nobody checks me.
1210
1211 >>> import random
1212 >>> print random.random() # doctest: +SKIP
1213 0.721216923889
1214
Edward Loper71f55af2004-08-26 01:41:51 +00001215The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001216and actual outputs to be displayed using a unified diff:
1217
1218 >>> def f(x):
1219 ... r'''
1220 ... >>> print '\n'.join('abcdefg')
1221 ... a
1222 ... B
1223 ... c
1224 ... d
1225 ... f
1226 ... g
1227 ... h
1228 ... '''
1229
1230 >>> # Without the flag:
1231 >>> test = doctest.DocTestFinder().find(f)[0]
1232 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001233 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001234 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001235 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001236 Failed example:
1237 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001238 Expected:
1239 a
1240 B
1241 c
1242 d
1243 f
1244 g
1245 h
1246 Got:
1247 a
1248 b
1249 c
1250 d
1251 e
1252 f
1253 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001254 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001255
1256 >>> # With the flag:
1257 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001258 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001259 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001260 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001261 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001262 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001263 Failed example:
1264 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001265 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001266 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001267 a
1268 -B
1269 +b
1270 c
1271 d
1272 +e
1273 f
1274 g
1275 -h
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001276 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001277
Edward Loper71f55af2004-08-26 01:41:51 +00001278The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001279and actual outputs to be displayed using a context diff:
1280
Edward Loper71f55af2004-08-26 01:41:51 +00001281 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001282 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001283 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001284 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001285 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001286 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001287 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001288 Failed example:
1289 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001290 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001291 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001292 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001293 a
1294 ! B
1295 c
1296 d
1297 f
1298 g
1299 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001300 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001301 a
1302 ! b
1303 c
1304 d
1305 + e
1306 f
1307 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001308 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001309
1310
Edward Loper71f55af2004-08-26 01:41:51 +00001311The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001312used by the popular ndiff.py utility. This does intraline difference
1313marking, as well as interline differences.
1314
1315 >>> def f(x):
1316 ... r'''
1317 ... >>> print "a b c d e f g h i j k l m"
1318 ... a b c d e f g h i j k 1 m
1319 ... '''
1320 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001321 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001322 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001323 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001324 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001325 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001326 Failed example:
1327 print "a b c d e f g h i j k l m"
1328 Differences (ndiff with -expected +actual):
1329 - a b c d e f g h i j k 1 m
1330 ? ^
1331 + a b c d e f g h i j k l m
1332 ? + ++ ^
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001333 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001334
Ezio Melottic2077b02011-03-16 12:34:31 +02001335The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001336failing example:
1337
1338 >>> def f(x):
1339 ... r'''
1340 ... >>> print 1 # first success
1341 ... 1
1342 ... >>> print 2 # first failure
1343 ... 200
1344 ... >>> print 3 # second failure
1345 ... 300
1346 ... >>> print 4 # second success
1347 ... 4
1348 ... >>> print 5 # third failure
1349 ... 500
1350 ... '''
1351 >>> test = doctest.DocTestFinder().find(f)[0]
1352 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1353 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001354 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001355 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001356 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001357 Failed example:
1358 print 2 # first failure
1359 Expected:
1360 200
1361 Got:
1362 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001363 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001364
Ezio Melottic2077b02011-03-16 12:34:31 +02001365However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001366
1367 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001368 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001369 Trying:
1370 print 1 # first success
1371 Expecting:
1372 1
1373 ok
1374 Trying:
1375 print 2 # first failure
1376 Expecting:
1377 200
1378 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001379 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001380 Failed example:
1381 print 2 # first failure
1382 Expected:
1383 200
1384 Got:
1385 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001386 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001387
1388For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1389count as failures:
1390
1391 >>> def f(x):
1392 ... r'''
1393 ... >>> print 1 # first success
1394 ... 1
1395 ... >>> raise ValueError(2) # first failure
1396 ... 200
1397 ... >>> print 3 # second failure
1398 ... 300
1399 ... >>> print 4 # second success
1400 ... 4
1401 ... >>> print 5 # third failure
1402 ... 500
1403 ... '''
1404 >>> test = doctest.DocTestFinder().find(f)[0]
1405 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1406 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1407 ... # doctest: +ELLIPSIS
1408 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001409 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001410 Failed example:
1411 raise ValueError(2) # first failure
1412 Exception raised:
1413 ...
1414 ValueError: 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001415 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001416
Tim Petersad2ef332006-05-10 02:43:01 +00001417New option flags can also be registered, via register_optionflag(). Here
1418we reach into doctest's internals a bit.
1419
1420 >>> unlikely = "UNLIKELY_OPTION_NAME"
1421 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1422 False
1423 >>> new_flag_value = doctest.register_optionflag(unlikely)
1424 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1425 True
1426
1427Before 2.4.4/2.5, registering a name more than once erroneously created
1428more than one flag value. Here we verify that's fixed:
1429
1430 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1431 >>> redundant_flag_value == new_flag_value
1432 True
1433
1434Clean up.
1435 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1436
Tim Petersc6cbab02004-08-22 19:43:28 +00001437 """
1438
Tim Peters8485b562004-08-04 18:46:34 +00001439 def option_directives(): r"""
1440Tests of `DocTestRunner`'s option directive mechanism.
1441
Edward Loper74bca7a2004-08-12 02:27:44 +00001442Option directives can be used to turn option flags on or off for a
1443single example. To turn an option on for an example, follow that
1444example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001445
1446 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001447 ... >>> print range(10) # should fail: no ellipsis
1448 ... [0, 1, ..., 9]
1449 ...
1450 ... >>> print range(10) # doctest: +ELLIPSIS
1451 ... [0, 1, ..., 9]
1452 ... '''
1453 >>> test = doctest.DocTestFinder().find(f)[0]
1454 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001455 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001456 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001457 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001458 Failed example:
1459 print range(10) # should fail: no ellipsis
1460 Expected:
1461 [0, 1, ..., 9]
1462 Got:
1463 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001464 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001465
1466To turn an option off for an example, follow that example with a
1467comment of the form ``# doctest: -OPTION``:
1468
1469 >>> def f(x): r'''
1470 ... >>> print range(10)
1471 ... [0, 1, ..., 9]
1472 ...
1473 ... >>> # should fail: no ellipsis
1474 ... >>> print range(10) # doctest: -ELLIPSIS
1475 ... [0, 1, ..., 9]
1476 ... '''
1477 >>> test = doctest.DocTestFinder().find(f)[0]
1478 >>> doctest.DocTestRunner(verbose=False,
1479 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001480 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001481 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001482 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001483 Failed example:
1484 print range(10) # doctest: -ELLIPSIS
1485 Expected:
1486 [0, 1, ..., 9]
1487 Got:
1488 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001489 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001490
1491Option directives affect only the example that they appear with; they
1492do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001493
Edward Loper74bca7a2004-08-12 02:27:44 +00001494 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001495 ... >>> print range(10) # Should fail: no ellipsis
1496 ... [0, 1, ..., 9]
1497 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001498 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001499 ... [0, 1, ..., 9]
1500 ...
Tim Peters8485b562004-08-04 18:46:34 +00001501 ... >>> print range(10) # Should fail: no ellipsis
1502 ... [0, 1, ..., 9]
1503 ... '''
1504 >>> test = doctest.DocTestFinder().find(f)[0]
1505 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001506 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001507 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001508 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001509 Failed example:
1510 print range(10) # Should fail: no ellipsis
1511 Expected:
1512 [0, 1, ..., 9]
1513 Got:
1514 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001515 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001516 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001517 Failed example:
1518 print range(10) # Should fail: no ellipsis
1519 Expected:
1520 [0, 1, ..., 9]
1521 Got:
1522 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001523 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001524
Edward Loper74bca7a2004-08-12 02:27:44 +00001525Multiple options may be modified by a single option directive. They
1526may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001527
1528 >>> def f(x): r'''
1529 ... >>> print range(10) # Should fail
1530 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001531 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001532 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001533 ... [0, 1, ..., 9]
1534 ... '''
1535 >>> test = doctest.DocTestFinder().find(f)[0]
1536 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001537 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001538 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001539 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001540 Failed example:
1541 print range(10) # Should fail
1542 Expected:
1543 [0, 1, ..., 9]
1544 Got:
1545 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001546 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001547
1548 >>> def f(x): r'''
1549 ... >>> print range(10) # Should fail
1550 ... [0, 1, ..., 9]
1551 ... >>> print range(10) # Should succeed
1552 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1553 ... [0, 1, ..., 9]
1554 ... '''
1555 >>> test = doctest.DocTestFinder().find(f)[0]
1556 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001557 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001558 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001559 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001560 Failed example:
1561 print range(10) # Should fail
1562 Expected:
1563 [0, 1, ..., 9]
1564 Got:
1565 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001566 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001567
1568 >>> def f(x): r'''
1569 ... >>> print range(10) # Should fail
1570 ... [0, 1, ..., 9]
1571 ... >>> print range(10) # Should succeed
1572 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1573 ... [0, 1, ..., 9]
1574 ... '''
1575 >>> test = doctest.DocTestFinder().find(f)[0]
1576 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001577 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001578 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001579 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001580 Failed example:
1581 print range(10) # Should fail
1582 Expected:
1583 [0, 1, ..., 9]
1584 Got:
1585 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001586 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001587
1588The option directive may be put on the line following the source, as
1589long as a continuation prompt is used:
1590
1591 >>> def f(x): r'''
1592 ... >>> print range(10)
1593 ... ... # doctest: +ELLIPSIS
1594 ... [0, 1, ..., 9]
1595 ... '''
1596 >>> test = doctest.DocTestFinder().find(f)[0]
1597 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001598 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001599
Edward Loper74bca7a2004-08-12 02:27:44 +00001600For examples with multi-line source, the option directive may appear
1601at the end of any line:
1602
1603 >>> def f(x): r'''
1604 ... >>> for x in range(10): # doctest: +ELLIPSIS
1605 ... ... print x,
1606 ... 0 1 2 ... 9
1607 ...
1608 ... >>> for x in range(10):
1609 ... ... print x, # doctest: +ELLIPSIS
1610 ... 0 1 2 ... 9
1611 ... '''
1612 >>> test = doctest.DocTestFinder().find(f)[0]
1613 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001614 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001615
1616If more than one line of an example with multi-line source has an
1617option directive, then they are combined:
1618
1619 >>> def f(x): r'''
1620 ... Should fail (option directive not on the last line):
1621 ... >>> for x in range(10): # doctest: +ELLIPSIS
1622 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1623 ... 0 1 2...9
1624 ... '''
1625 >>> test = doctest.DocTestFinder().find(f)[0]
1626 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001627 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001628
1629It is an error to have a comment of the form ``# doctest:`` that is
1630*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1631``OPTION`` is an option that has been registered with
1632`register_option`:
1633
1634 >>> # Error: Option not registered
1635 >>> s = '>>> print 12 #doctest: +BADOPTION'
1636 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1637 Traceback (most recent call last):
1638 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1639
1640 >>> # Error: No + or - prefix
1641 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1642 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1643 Traceback (most recent call last):
1644 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1645
1646It is an error to use an option directive on a line that contains no
1647source:
1648
1649 >>> s = '>>> # doctest: +ELLIPSIS'
1650 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1651 Traceback (most recent call last):
1652 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 +00001653
1654 """
1655
1656 def test_unicode_output(self): r"""
1657
1658Check that unicode output works:
1659
1660 >>> u'\xe9'
1661 u'\xe9'
1662
1663If we return unicode, SpoofOut's buf variable becomes automagically
1664converted to unicode. This means all subsequent output becomes converted
1665to unicode, and if the output contains non-ascii characters that failed.
1666It used to be that this state change carried on between tests, meaning
1667tests would fail if unicode has been output previously in the testrun.
1668This test tests that this is no longer so:
1669
1670 >>> print u'abc'
1671 abc
1672
1673And then return a string with non-ascii characters:
1674
1675 >>> print u'\xe9'.encode('utf-8')
1676 é
1677
1678 """
1679
Tim Peters8485b562004-08-04 18:46:34 +00001680
1681def test_testsource(): r"""
1682Unit tests for `testsource()`.
1683
1684The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001685test with that name in that module, and converts it to a script. The
1686example code is converted to regular Python code. The surrounding
1687words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001688
1689 >>> import test.test_doctest
1690 >>> name = 'test.test_doctest.sample_func'
1691 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001692 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001693 #
Tim Peters8485b562004-08-04 18:46:34 +00001694 print sample_func(22)
1695 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001696 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001697 #
Edward Lopera5db6002004-08-12 02:41:30 +00001698 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001699 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001700
1701 >>> name = 'test.test_doctest.SampleNewStyleClass'
1702 >>> print doctest.testsource(test.test_doctest, name)
1703 print '1\n2\n3'
1704 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001705 ## 1
1706 ## 2
1707 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001708 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001709
1710 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1711 >>> print doctest.testsource(test.test_doctest, name)
1712 print SampleClass.a_classmethod(10)
1713 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001714 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001715 print SampleClass(0).a_classmethod(10)
1716 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001717 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001718 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001719"""
1720
1721def test_debug(): r"""
1722
1723Create a docstring that we want to debug:
1724
1725 >>> s = '''
1726 ... >>> x = 12
1727 ... >>> print x
1728 ... 12
1729 ... '''
1730
1731Create some fake stdin input, to feed to the debugger:
1732
1733 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001734 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001735 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001736
1737Run the debugger on the docstring, and then restore sys.stdin.
1738
Edward Loper2de91ba2004-08-27 02:07:46 +00001739 >>> try: doctest.debug_src(s)
1740 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001741 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001742 (Pdb) next
1743 12
Tim Peters8485b562004-08-04 18:46:34 +00001744 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001745 > <string>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001746 (Pdb) print x
1747 12
1748 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001749
1750"""
1751
Jim Fulton356fd192004-08-09 11:34:47 +00001752def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001753 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001754
Tim Peters413ced62004-08-09 15:43:47 +00001755 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001756 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001757 you use it. The doctest module changes sys.stdout so that it can
1758 capture program output. It also temporarily replaces pdb.set_trace
1759 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001760 see debugger output.
1761
1762 >>> doc = '''
1763 ... >>> x = 42
Florent Xicluna80800d32010-10-14 21:46:04 +00001764 ... >>> raise Exception('clé')
1765 ... Traceback (most recent call last):
1766 ... Exception: clé
Jim Fulton356fd192004-08-09 11:34:47 +00001767 ... >>> import pdb; pdb.set_trace()
1768 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001769 >>> parser = doctest.DocTestParser()
Florent Xiclunab67660f2010-10-14 21:10:45 +00001770 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001771 >>> runner = doctest.DocTestRunner(verbose=False)
1772
1773 To demonstrate this, we'll create a fake standard input that
1774 captures our debugger input:
1775
1776 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001777 >>> real_stdin = sys.stdin
1778 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001779 ... 'print x', # print data defined by the example
1780 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001781 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001782
Edward Loper2de91ba2004-08-27 02:07:46 +00001783 >>> try: runner.run(test)
1784 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001785 --Return--
Florent Xicluna80800d32010-10-14 21:46:04 +00001786 > <doctest foo-bär@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001787 -> import pdb; pdb.set_trace()
1788 (Pdb) print x
1789 42
1790 (Pdb) continue
Florent Xicluna80800d32010-10-14 21:46:04 +00001791 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001792
1793 You can also put pdb.set_trace in a function called from a test:
1794
1795 >>> def calls_set_trace():
1796 ... y=2
1797 ... import pdb; pdb.set_trace()
1798
1799 >>> doc = '''
1800 ... >>> x=1
1801 ... >>> calls_set_trace()
1802 ... '''
Florent Xiclunab67660f2010-10-14 21:10:45 +00001803 >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001804 >>> real_stdin = sys.stdin
1805 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001806 ... 'print y', # print data defined in the function
1807 ... 'up', # out of function
1808 ... 'print x', # print data defined by the example
1809 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001810 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001811
Tim Peters50c6bdb2004-11-08 22:07:37 +00001812 >>> try:
1813 ... runner.run(test)
1814 ... finally:
1815 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001816 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001817 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1818 -> import pdb; pdb.set_trace()
1819 (Pdb) print y
1820 2
1821 (Pdb) up
Florent Xiclunab67660f2010-10-14 21:10:45 +00001822 > <doctest foo-bär@baz[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001823 -> calls_set_trace()
1824 (Pdb) print x
1825 1
1826 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001827 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001828
1829 During interactive debugging, source code is shown, even for
1830 doctest examples:
1831
1832 >>> doc = '''
1833 ... >>> def f(x):
1834 ... ... g(x*2)
1835 ... >>> def g(x):
1836 ... ... print x+3
1837 ... ... import pdb; pdb.set_trace()
1838 ... >>> f(3)
1839 ... '''
Florent Xiclunab67660f2010-10-14 21:10:45 +00001840 >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001841 >>> real_stdin = sys.stdin
1842 >>> sys.stdin = _FakeInput([
1843 ... 'list', # list source from example 2
1844 ... 'next', # return from g()
1845 ... 'list', # list source from example 1
1846 ... 'next', # return from f()
1847 ... 'list', # list source from example 3
1848 ... 'continue', # stop debugging
1849 ... ''])
1850 >>> try: runner.run(test)
1851 ... finally: sys.stdin = real_stdin
1852 ... # doctest: +NORMALIZE_WHITESPACE
1853 --Return--
Florent Xiclunab67660f2010-10-14 21:10:45 +00001854 > <doctest foo-bär@baz[1]>(3)g()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001855 -> import pdb; pdb.set_trace()
1856 (Pdb) list
1857 1 def g(x):
1858 2 print x+3
1859 3 -> import pdb; pdb.set_trace()
1860 [EOF]
1861 (Pdb) next
1862 --Return--
Florent Xiclunab67660f2010-10-14 21:10:45 +00001863 > <doctest foo-bär@baz[0]>(2)f()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001864 -> g(x*2)
1865 (Pdb) list
1866 1 def f(x):
1867 2 -> g(x*2)
1868 [EOF]
1869 (Pdb) next
1870 --Return--
Florent Xiclunab67660f2010-10-14 21:10:45 +00001871 > <doctest foo-bär@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001872 -> f(3)
1873 (Pdb) list
1874 1 -> f(3)
1875 [EOF]
1876 (Pdb) continue
1877 **********************************************************************
Florent Xiclunab67660f2010-10-14 21:10:45 +00001878 File "foo-bär@baz.py", line 7, in foo-bär@baz
Edward Loper2de91ba2004-08-27 02:07:46 +00001879 Failed example:
1880 f(3)
1881 Expected nothing
1882 Got:
1883 9
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001884 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001885 """
1886
Tim Peters50c6bdb2004-11-08 22:07:37 +00001887def test_pdb_set_trace_nested():
1888 """This illustrates more-demanding use of set_trace with nested functions.
1889
1890 >>> class C(object):
1891 ... def calls_set_trace(self):
1892 ... y = 1
1893 ... import pdb; pdb.set_trace()
1894 ... self.f1()
1895 ... y = 2
1896 ... def f1(self):
1897 ... x = 1
1898 ... self.f2()
1899 ... x = 2
1900 ... def f2(self):
1901 ... z = 1
1902 ... z = 2
1903
1904 >>> calls_set_trace = C().calls_set_trace
1905
1906 >>> doc = '''
1907 ... >>> a = 1
1908 ... >>> calls_set_trace()
1909 ... '''
1910 >>> parser = doctest.DocTestParser()
1911 >>> runner = doctest.DocTestRunner(verbose=False)
Florent Xiclunab67660f2010-10-14 21:10:45 +00001912 >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001913 >>> real_stdin = sys.stdin
1914 >>> sys.stdin = _FakeInput([
1915 ... 'print y', # print data defined in the function
1916 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z',
1917 ... 'up', 'print x',
1918 ... 'up', 'print y',
1919 ... 'up', 'print foo',
1920 ... 'continue', # stop debugging
1921 ... ''])
1922
1923 >>> try:
1924 ... runner.run(test)
1925 ... finally:
1926 ... sys.stdin = real_stdin
1927 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1928 -> self.f1()
1929 (Pdb) print y
1930 1
1931 (Pdb) step
1932 --Call--
1933 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1934 -> def f1(self):
1935 (Pdb) step
1936 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1937 -> x = 1
1938 (Pdb) step
1939 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1940 -> self.f2()
1941 (Pdb) step
1942 --Call--
1943 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1944 -> def f2(self):
1945 (Pdb) step
1946 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1947 -> z = 1
1948 (Pdb) step
1949 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1950 -> z = 2
1951 (Pdb) print z
1952 1
1953 (Pdb) up
1954 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1955 -> self.f2()
1956 (Pdb) print x
1957 1
1958 (Pdb) up
1959 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1960 -> self.f1()
1961 (Pdb) print y
1962 1
1963 (Pdb) up
Florent Xiclunab67660f2010-10-14 21:10:45 +00001964 > <doctest foo-bär@baz[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001965 -> calls_set_trace()
1966 (Pdb) print foo
1967 *** NameError: name 'foo' is not defined
1968 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001969 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001970"""
1971
Tim Peters19397e52004-08-06 22:02:59 +00001972def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001973 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001974
1975 We create a Suite by providing a module. A module can be provided
1976 by passing a module object:
1977
1978 >>> import unittest
1979 >>> import test.sample_doctest
1980 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1981 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001982 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001983
1984 We can also supply the module by name:
1985
1986 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1987 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001988 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001989
1990 We can use the current module:
1991
1992 >>> suite = test.sample_doctest.test_suite()
1993 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001994 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001995
1996 We can supply global variables. If we pass globs, they will be
1997 used instead of the module globals. Here we'll pass an empty
1998 globals, triggering an extra error:
1999
2000 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2001 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002002 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002003
2004 Alternatively, we can provide extra globals. Here we'll make an
2005 error go away by providing an extra global variable:
2006
2007 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2008 ... extraglobs={'y': 1})
2009 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002010 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002011
2012 You can pass option flags. Here we'll cause an extra error
2013 by disabling the blank-line feature:
2014
2015 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002016 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002017 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002018 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002019
Tim Peters1e277ee2004-08-07 05:37:52 +00002020 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002021
Jim Fultonf54bad42004-08-28 14:57:56 +00002022 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002023 ... import test.test_doctest
2024 ... test.test_doctest.sillySetup = True
2025
Jim Fultonf54bad42004-08-28 14:57:56 +00002026 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002027 ... import test.test_doctest
2028 ... del test.test_doctest.sillySetup
2029
2030 Here, we installed a silly variable that the test expects:
2031
2032 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2033 ... setUp=setUp, tearDown=tearDown)
2034 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002035 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002036
2037 But the tearDown restores sanity:
2038
2039 >>> import test.test_doctest
2040 >>> test.test_doctest.sillySetup
2041 Traceback (most recent call last):
2042 ...
2043 AttributeError: 'module' object has no attribute 'sillySetup'
2044
Jim Fultonf54bad42004-08-28 14:57:56 +00002045 The setUp and tearDown funtions are passed test objects. Here
2046 we'll use the setUp function to supply the missing variable y:
2047
2048 >>> def setUp(test):
2049 ... test.globs['y'] = 1
2050
2051 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2052 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002053 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002054
2055 Here, we didn't need to use a tearDown function because we
2056 modified the test globals, which are a copy of the
2057 sample_doctest module dictionary. The test globals are
2058 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002059 """
2060
2061def test_DocFileSuite():
2062 """We can test tests found in text files using a DocFileSuite.
2063
2064 We create a suite by providing the names of one or more text
2065 files that include examples:
2066
2067 >>> import unittest
2068 >>> suite = doctest.DocFileSuite('test_doctest.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002069 ... 'test_doctest2.txt',
2070 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002071 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002072 <unittest.result.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002073
2074 The test files are looked for in the directory containing the
2075 calling module. A package keyword argument can be provided to
2076 specify a different relative location.
2077
2078 >>> import unittest
2079 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2080 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002081 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002082 ... package='test')
2083 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002084 <unittest.result.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002085
Brett Cannon43e53f82007-11-21 00:47:36 +00002086 Support for using a package's __loader__.get_data() is also
2087 provided.
2088
2089 >>> import unittest, pkgutil, test
Brett Cannoneaa2c982007-11-23 00:06:51 +00002090 >>> added_loader = False
Brett Cannon43e53f82007-11-21 00:47:36 +00002091 >>> if not hasattr(test, '__loader__'):
2092 ... test.__loader__ = pkgutil.get_loader(test)
2093 ... added_loader = True
2094 >>> try:
2095 ... suite = doctest.DocFileSuite('test_doctest.txt',
2096 ... 'test_doctest2.txt',
2097 ... 'test_doctest4.txt',
2098 ... package='test')
2099 ... suite.run(unittest.TestResult())
2100 ... finally:
Brett Cannon9db1d5a2007-11-21 00:58:03 +00002101 ... if added_loader:
2102 ... del test.__loader__
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002103 <unittest.result.TestResult run=3 errors=0 failures=3>
Brett Cannon43e53f82007-11-21 00:47:36 +00002104
Edward Loper0273f5b2004-09-18 20:27:04 +00002105 '/' should be used as a path separator. It will be converted
2106 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002107
2108 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2109 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002110 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002111
Edward Loper0273f5b2004-09-18 20:27:04 +00002112 If DocFileSuite is used from an interactive session, then files
2113 are resolved relative to the directory of sys.argv[0]:
2114
Christian Heimesc756d002007-11-27 21:34:01 +00002115 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002116 >>> save_argv = sys.argv
2117 >>> sys.argv = [test.test_doctest.__file__]
2118 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimesc756d002007-11-27 21:34:01 +00002119 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002120 >>> sys.argv = save_argv
2121
Edward Loper052d0cd2004-09-19 17:19:33 +00002122 By setting `module_relative=False`, os-specific paths may be
2123 used (including absolute paths and paths relative to the
2124 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002125
2126 >>> # Get the absolute path of the test package.
2127 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2128 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2129
2130 >>> # Use it to find the absolute path of test_doctest.txt.
2131 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2132
Edward Loper052d0cd2004-09-19 17:19:33 +00002133 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002134 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002135 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002136
Edward Loper052d0cd2004-09-19 17:19:33 +00002137 It is an error to specify `package` when `module_relative=False`:
2138
2139 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2140 ... package='test')
2141 Traceback (most recent call last):
2142 ValueError: Package may only be specified for module-relative paths.
2143
Tim Peters19397e52004-08-06 22:02:59 +00002144 You can specify initial global variables:
2145
2146 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2147 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002148 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002149 ... globs={'favorite_color': 'blue'})
2150 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002151 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002152
2153 In this case, we supplied a missing favorite color. You can
2154 provide doctest options:
2155
2156 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2157 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002158 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002159 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2160 ... globs={'favorite_color': 'blue'})
2161 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002162 <unittest.result.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002163
2164 And, you can provide setUp and tearDown functions:
2165
Jim Fultonf54bad42004-08-28 14:57:56 +00002166 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002167 ... import test.test_doctest
2168 ... test.test_doctest.sillySetup = True
2169
Jim Fultonf54bad42004-08-28 14:57:56 +00002170 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002171 ... import test.test_doctest
2172 ... del test.test_doctest.sillySetup
2173
2174 Here, we installed a silly variable that the test expects:
2175
2176 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2177 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002178 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002179 ... setUp=setUp, tearDown=tearDown)
2180 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002181 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002182
2183 But the tearDown restores sanity:
2184
2185 >>> import test.test_doctest
2186 >>> test.test_doctest.sillySetup
2187 Traceback (most recent call last):
2188 ...
2189 AttributeError: 'module' object has no attribute 'sillySetup'
2190
Jim Fultonf54bad42004-08-28 14:57:56 +00002191 The setUp and tearDown funtions are passed test objects.
2192 Here, we'll use a setUp function to set the favorite color in
2193 test_doctest.txt:
2194
2195 >>> def setUp(test):
2196 ... test.globs['favorite_color'] = 'blue'
2197
2198 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2199 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002200 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002201
2202 Here, we didn't need to use a tearDown function because we
2203 modified the test globals. The test globals are
2204 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002205
Fred Drake7c404a42004-12-21 23:46:34 +00002206 Tests in a file run using `DocFileSuite` can also access the
2207 `__file__` global, which is set to the name of the file
2208 containing the tests:
2209
2210 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2211 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002212 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002213
George Yoshidaf3c65de2006-05-28 16:39:09 +00002214 If the tests contain non-ASCII characters, we have to specify which
2215 encoding the file is encoded with. We do so by using the `encoding`
2216 parameter:
2217
2218 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2219 ... 'test_doctest2.txt',
2220 ... 'test_doctest4.txt',
2221 ... encoding='utf-8')
2222 >>> suite.run(unittest.TestResult())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00002223 <unittest.result.TestResult run=3 errors=0 failures=2>
George Yoshidaf3c65de2006-05-28 16:39:09 +00002224
Jim Fultonf54bad42004-08-28 14:57:56 +00002225 """
Tim Peters19397e52004-08-06 22:02:59 +00002226
Jim Fulton07a349c2004-08-22 14:10:00 +00002227def test_trailing_space_in_test():
2228 """
Tim Petersa7def722004-08-23 22:13:22 +00002229 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002230
Jim Fulton07a349c2004-08-22 14:10:00 +00002231 >>> x, y = 'foo', ''
2232 >>> print x, y
2233 foo \n
2234 """
Tim Peters19397e52004-08-06 22:02:59 +00002235
Jim Fultonf54bad42004-08-28 14:57:56 +00002236
2237def test_unittest_reportflags():
2238 """Default unittest reporting flags can be set to control reporting
2239
2240 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2241 only the first failure of each test. First, we'll look at the
2242 output without the flag. The file test_doctest.txt file has two
2243 tests. They both fail if blank lines are disabled:
2244
2245 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2246 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2247 >>> import unittest
2248 >>> result = suite.run(unittest.TestResult())
2249 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2250 Traceback ...
2251 Failed example:
2252 favorite_color
2253 ...
2254 Failed example:
2255 if 1:
2256 ...
2257
2258 Note that we see both failures displayed.
2259
2260 >>> old = doctest.set_unittest_reportflags(
2261 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2262
2263 Now, when we run the test:
2264
2265 >>> result = suite.run(unittest.TestResult())
2266 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2267 Traceback ...
2268 Failed example:
2269 favorite_color
2270 Exception raised:
2271 ...
2272 NameError: name 'favorite_color' is not defined
2273 <BLANKLINE>
2274 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002275
Jim Fultonf54bad42004-08-28 14:57:56 +00002276 We get only the first failure.
2277
2278 If we give any reporting options when we set up the tests,
2279 however:
2280
2281 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2282 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2283
2284 Then the default eporting options are ignored:
2285
2286 >>> result = suite.run(unittest.TestResult())
2287 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2288 Traceback ...
2289 Failed example:
2290 favorite_color
2291 ...
2292 Failed example:
2293 if 1:
2294 print 'a'
2295 print
2296 print 'b'
2297 Differences (ndiff with -expected +actual):
2298 a
2299 - <BLANKLINE>
2300 +
2301 b
2302 <BLANKLINE>
2303 <BLANKLINE>
2304
2305
2306 Test runners can restore the formatting flags after they run:
2307
2308 >>> ignored = doctest.set_unittest_reportflags(old)
2309
2310 """
2311
Edward Loper052d0cd2004-09-19 17:19:33 +00002312def test_testfile(): r"""
2313Tests for the `testfile()` function. This function runs all the
2314doctest examples in a given file. In its simple invokation, it is
2315called with the name of a file, which is taken to be relative to the
2316calling module. The return value is (#failures, #tests).
2317
Florent Xicluna2a903b22010-02-27 13:31:23 +00002318We don't want `-v` in sys.argv for these tests.
2319
2320 >>> save_argv = sys.argv
2321 >>> if '-v' in sys.argv:
2322 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2323
2324
Edward Loper052d0cd2004-09-19 17:19:33 +00002325 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2326 **********************************************************************
2327 File "...", line 6, in test_doctest.txt
2328 Failed example:
2329 favorite_color
2330 Exception raised:
2331 ...
2332 NameError: name 'favorite_color' is not defined
2333 **********************************************************************
2334 1 items had failures:
2335 1 of 2 in test_doctest.txt
2336 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002337 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002338 >>> doctest.master = None # Reset master.
2339
2340(Note: we'll be clearing doctest.master after each call to
Florent Xicluna07627882010-03-21 01:14:24 +00002341`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002342same name.)
2343
2344Globals may be specified with the `globs` and `extraglobs` parameters:
2345
2346 >>> globs = {'favorite_color': 'blue'}
2347 >>> doctest.testfile('test_doctest.txt', globs=globs)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002348 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002349 >>> doctest.master = None # Reset master.
2350
2351 >>> extraglobs = {'favorite_color': 'red'}
2352 >>> doctest.testfile('test_doctest.txt', globs=globs,
2353 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2354 **********************************************************************
2355 File "...", line 6, in test_doctest.txt
2356 Failed example:
2357 favorite_color
2358 Expected:
2359 'blue'
2360 Got:
2361 'red'
2362 **********************************************************************
2363 1 items had failures:
2364 1 of 2 in test_doctest.txt
2365 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002366 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002367 >>> doctest.master = None # Reset master.
2368
2369The file may be made relative to a given module or package, using the
2370optional `module_relative` parameter:
2371
2372 >>> doctest.testfile('test_doctest.txt', globs=globs,
2373 ... module_relative='test')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002374 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002375 >>> doctest.master = None # Reset master.
2376
Ezio Melottic2077b02011-03-16 12:34:31 +02002377Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002378
2379 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2380 Trying:
2381 favorite_color
2382 Expecting:
2383 'blue'
2384 ok
2385 Trying:
2386 if 1:
2387 print 'a'
2388 print
2389 print 'b'
2390 Expecting:
2391 a
2392 <BLANKLINE>
2393 b
2394 ok
2395 1 items passed all tests:
2396 2 tests in test_doctest.txt
2397 2 tests in 1 items.
2398 2 passed and 0 failed.
2399 Test passed.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002400 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002401 >>> doctest.master = None # Reset master.
2402
2403The name of the test may be specified with the optional `name`
2404parameter:
2405
2406 >>> doctest.testfile('test_doctest.txt', name='newname')
2407 ... # doctest: +ELLIPSIS
2408 **********************************************************************
2409 File "...", line 6, in newname
2410 ...
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002411 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002412 >>> doctest.master = None # Reset master.
2413
Ezio Melottic2077b02011-03-16 12:34:31 +02002414The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002415parameter:
2416
2417 >>> doctest.testfile('test_doctest.txt', report=False)
2418 ... # doctest: +ELLIPSIS
2419 **********************************************************************
2420 File "...", line 6, in test_doctest.txt
2421 Failed example:
2422 favorite_color
2423 Exception raised:
2424 ...
2425 NameError: name 'favorite_color' is not defined
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002426 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002427 >>> doctest.master = None # Reset master.
2428
2429The optional keyword argument `raise_on_error` can be used to raise an
2430exception on the first error (which may be useful for postmortem
2431debugging):
2432
2433 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2434 ... # doctest: +ELLIPSIS
2435 Traceback (most recent call last):
2436 UnexpectedException: ...
2437 >>> doctest.master = None # Reset master.
George Yoshidaf3c65de2006-05-28 16:39:09 +00002438
2439If the tests contain non-ASCII characters, the tests might fail, since
2440it's unknown which encoding is used. The encoding can be specified
2441using the optional keyword argument `encoding`:
2442
2443 >>> doctest.testfile('test_doctest4.txt') # doctest: +ELLIPSIS
2444 **********************************************************************
2445 File "...", line 7, in test_doctest4.txt
2446 Failed example:
2447 u'...'
2448 Expected:
2449 u'f\xf6\xf6'
2450 Got:
2451 u'f\xc3\xb6\xc3\xb6'
2452 **********************************************************************
2453 ...
2454 **********************************************************************
2455 1 items had failures:
2456 2 of 4 in test_doctest4.txt
2457 ***Test Failed*** 2 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002458 TestResults(failed=2, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002459 >>> doctest.master = None # Reset master.
2460
2461 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002462 TestResults(failed=0, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002463 >>> doctest.master = None # Reset master.
Florent Xicluna2a903b22010-02-27 13:31:23 +00002464
2465Switch the module encoding to 'utf-8' to test the verbose output without
2466bothering with the current sys.stdout encoding.
2467
2468 >>> doctest._encoding, saved_encoding = 'utf-8', doctest._encoding
2469 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2470 Trying:
2471 u'föö'
2472 Expecting:
2473 u'f\xf6\xf6'
2474 ok
2475 Trying:
2476 u'bÄ…r'
2477 Expecting:
2478 u'b\u0105r'
2479 ok
2480 Trying:
2481 'föö'
2482 Expecting:
2483 'f\xc3\xb6\xc3\xb6'
2484 ok
2485 Trying:
2486 'bÄ…r'
2487 Expecting:
2488 'b\xc4\x85r'
2489 ok
2490 1 items passed all tests:
2491 4 tests in test_doctest4.txt
2492 4 tests in 1 items.
2493 4 passed and 0 failed.
2494 Test passed.
2495 TestResults(failed=0, attempted=4)
2496 >>> doctest._encoding = saved_encoding
2497 >>> doctest.master = None # Reset master.
2498 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002499"""
2500
Tim Petersa7def722004-08-23 22:13:22 +00002501# old_test1, ... used to live in doctest.py, but cluttered it. Note
2502# that these use the deprecated doctest.Tester, so should go away (or
2503# be rewritten) someday.
2504
Tim Petersa7def722004-08-23 22:13:22 +00002505def old_test1(): r"""
2506>>> from doctest import Tester
2507>>> t = Tester(globs={'x': 42}, verbose=0)
2508>>> t.runstring(r'''
2509... >>> x = x * 2
2510... >>> print x
2511... 42
2512... ''', 'XYZ')
2513**********************************************************************
2514Line 3, in XYZ
2515Failed example:
2516 print x
2517Expected:
2518 42
2519Got:
2520 84
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002521TestResults(failed=1, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002522>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002523TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002524>>> t.summarize()
2525**********************************************************************
25261 items had failures:
2527 1 of 2 in XYZ
2528***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002529TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002530>>> t.summarize(verbose=1)
25311 items passed all tests:
2532 2 tests in example2
2533**********************************************************************
25341 items had failures:
2535 1 of 2 in XYZ
25364 tests in 2 items.
25373 passed and 1 failed.
2538***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002539TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002540"""
2541
2542def old_test2(): r"""
2543 >>> from doctest import Tester
2544 >>> t = Tester(globs={}, verbose=1)
2545 >>> test = r'''
2546 ... # just an example
2547 ... >>> x = 1 + 2
2548 ... >>> x
2549 ... 3
2550 ... '''
2551 >>> t.runstring(test, "Example")
2552 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002553 Trying:
2554 x = 1 + 2
2555 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002556 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002557 Trying:
2558 x
2559 Expecting:
2560 3
Tim Petersa7def722004-08-23 22:13:22 +00002561 ok
2562 0 of 2 examples failed in string Example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002563 TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002564"""
2565
2566def old_test3(): r"""
2567 >>> from doctest import Tester
2568 >>> t = Tester(globs={}, verbose=0)
2569 >>> def _f():
2570 ... '''Trivial docstring example.
2571 ... >>> assert 2 == 2
2572 ... '''
2573 ... return 32
2574 ...
2575 >>> t.rundoc(_f) # expect 0 failures in 1 example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002576 TestResults(failed=0, attempted=1)
Tim Petersa7def722004-08-23 22:13:22 +00002577"""
2578
2579def old_test4(): """
Christian Heimesc756d002007-11-27 21:34:01 +00002580 >>> import types
2581 >>> m1 = types.ModuleType('_m1')
2582 >>> m2 = types.ModuleType('_m2')
Tim Petersa7def722004-08-23 22:13:22 +00002583 >>> test_data = \"""
2584 ... def _f():
2585 ... '''>>> assert 1 == 1
2586 ... '''
2587 ... def g():
2588 ... '''>>> assert 2 != 1
2589 ... '''
2590 ... class H:
2591 ... '''>>> assert 2 > 1
2592 ... '''
2593 ... def bar(self):
2594 ... '''>>> assert 1 < 2
2595 ... '''
2596 ... \"""
2597 >>> exec test_data in m1.__dict__
2598 >>> exec test_data in m2.__dict__
2599 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2600
2601 Tests that objects outside m1 are excluded:
2602
2603 >>> from doctest import Tester
2604 >>> t = Tester(globs={}, verbose=0)
2605 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002606 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002607
2608 Once more, not excluding stuff outside m1:
2609
2610 >>> t = Tester(globs={}, verbose=0)
2611 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002612 TestResults(failed=0, attempted=8)
Tim Petersa7def722004-08-23 22:13:22 +00002613
2614 The exclusion of objects from outside the designated module is
2615 meant to be invoked automagically by testmod.
2616
2617 >>> doctest.testmod(m1, verbose=False)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002618 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002619"""
2620
Tim Peters8485b562004-08-04 18:46:34 +00002621######################################################################
2622## Main
2623######################################################################
2624
2625def test_main():
2626 # Check the doctest cases in doctest itself:
2627 test_support.run_doctest(doctest, verbosity=True)
Florent Xicluna07627882010-03-21 01:14:24 +00002628
Tim Peters8485b562004-08-04 18:46:34 +00002629 from test import test_doctest
Florent Xicluna6257a7b2010-03-31 22:01:03 +00002630
2631 # Ignore all warnings about the use of class Tester in this module.
2632 deprecations = [("class Tester is deprecated", DeprecationWarning)]
2633 if sys.py3kwarning:
2634 deprecations += [("backquote not supported", SyntaxWarning),
2635 ("execfile.. not supported", DeprecationWarning)]
2636 with test_support.check_warnings(*deprecations):
Florent Xicluna07627882010-03-21 01:14:24 +00002637 # Check the doctest cases defined here:
2638 test_support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002639
Victor Stinneredb9f872010-04-27 21:51:26 +00002640import sys
Tim Peters8485b562004-08-04 18:46:34 +00002641def test_coverage(coverdir):
Victor Stinneredb9f872010-04-27 21:51:26 +00002642 trace = test_support.import_module('trace')
Tim Peters8485b562004-08-04 18:46:34 +00002643 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2644 trace=0, count=1)
2645 tracer.run('reload(doctest); test_main()')
2646 r = tracer.results()
2647 print 'Writing coverage results...'
2648 r.write_results(show_missing=True, summary=True,
2649 coverdir=coverdir)
2650
2651if __name__ == '__main__':
2652 if '-c' in sys.argv:
2653 test_coverage('/tmp/doctest.cover')
2654 else:
2655 test_main()