blob: 7ce3e3b98139a385072d74a0f2502fb5bdf3c58e [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Barry Warsaw04f357c2002-07-23 19:04:11 +00005from test import test_support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Tim Petersa7def722004-08-23 22:13:22 +00007import warnings
Tim Peters8485b562004-08-04 18:46:34 +00008
9######################################################################
10## Sample Objects (used by test cases)
11######################################################################
12
13def sample_func(v):
14 """
Tim Peters19397e52004-08-06 22:02:59 +000015 Blah blah
16
Tim Peters8485b562004-08-04 18:46:34 +000017 >>> print sample_func(22)
18 44
Tim Peters19397e52004-08-06 22:02:59 +000019
20 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000021 """
22 return v+v
23
24class SampleClass:
25 """
26 >>> print 1
27 1
28 """
29 def __init__(self, val):
30 """
31 >>> print SampleClass(12).get()
32 12
33 """
34 self.val = val
35
36 def double(self):
37 """
38 >>> print SampleClass(12).double().get()
39 24
40 """
41 return SampleClass(self.val + self.val)
42
43 def get(self):
44 """
45 >>> print SampleClass(-5).get()
46 -5
47 """
48 return self.val
49
50 def a_staticmethod(v):
51 """
52 >>> print SampleClass.a_staticmethod(10)
53 11
54 """
55 return v+1
56 a_staticmethod = staticmethod(a_staticmethod)
57
58 def a_classmethod(cls, v):
59 """
60 >>> print SampleClass.a_classmethod(10)
61 12
62 >>> print SampleClass(0).a_classmethod(10)
63 12
64 """
65 return v+2
66 a_classmethod = classmethod(a_classmethod)
67
68 a_property = property(get, doc="""
69 >>> print SampleClass(22).a_property
70 22
71 """)
72
73 class NestedClass:
74 """
75 >>> x = SampleClass.NestedClass(5)
76 >>> y = x.square()
77 >>> print y.get()
78 25
79 """
80 def __init__(self, val=0):
81 """
82 >>> print SampleClass.NestedClass().get()
83 0
84 """
85 self.val = val
86 def square(self):
87 return SampleClass.NestedClass(self.val*self.val)
88 def get(self):
89 return self.val
90
91class SampleNewStyleClass(object):
92 r"""
93 >>> print '1\n2\n3'
94 1
95 2
96 3
97 """
98 def __init__(self, val):
99 """
100 >>> print SampleNewStyleClass(12).get()
101 12
102 """
103 self.val = val
104
105 def double(self):
106 """
107 >>> print SampleNewStyleClass(12).double().get()
108 24
109 """
110 return SampleNewStyleClass(self.val + self.val)
111
112 def get(self):
113 """
114 >>> print SampleNewStyleClass(-5).get()
115 -5
116 """
117 return self.val
118
119######################################################################
120## Test Cases
121######################################################################
122
123def test_Example(): r"""
124Unit tests for the `Example` class.
125
Edward Lopera6b68322004-08-26 00:05:43 +0000126Example is a simple container class that holds:
127 - `source`: A source string.
128 - `want`: An expected output string.
129 - `exc_msg`: An expected exception message string (or None if no
130 exception is expected).
131 - `lineno`: A line number (within the docstring).
132 - `indent`: The example's indentation in the input string.
133 - `options`: An option dictionary, mapping option flags to True or
134 False.
Tim Peters8485b562004-08-04 18:46:34 +0000135
Edward Lopera6b68322004-08-26 00:05:43 +0000136These attributes are set by the constructor. `source` and `want` are
137required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000138
Edward Lopera6b68322004-08-26 00:05:43 +0000139 >>> example = doctest.Example('print 1', '1\n')
140 >>> (example.source, example.want, example.exc_msg,
141 ... example.lineno, example.indent, example.options)
142 ('print 1\n', '1\n', None, 0, 0, {})
143
144The first three attributes (`source`, `want`, and `exc_msg`) may be
145specified positionally; the remaining arguments should be specified as
146keyword arguments:
147
148 >>> exc_msg = 'IndexError: pop from an empty list'
149 >>> example = doctest.Example('[].pop()', '', exc_msg,
150 ... lineno=5, indent=4,
151 ... options={doctest.ELLIPSIS: True})
152 >>> (example.source, example.want, example.exc_msg,
153 ... example.lineno, example.indent, example.options)
154 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
155
156The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000157
Tim Petersbb431472004-08-09 03:51:46 +0000158 Source spans a single line: no terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000159 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000160 >>> e.source, e.want
161 ('print 1\n', '1\n')
162
Edward Lopera6b68322004-08-26 00:05:43 +0000163 >>> e = doctest.Example('print 1\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000164 >>> e.source, e.want
165 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000166
Tim Petersbb431472004-08-09 03:51:46 +0000167 Source spans multiple lines: require terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000168 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000169 >>> e.source, e.want
170 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000171
Edward Lopera6b68322004-08-26 00:05:43 +0000172 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000173 >>> e.source, e.want
174 ('print 1;\nprint 2\n', '1\n2\n')
175
Edward Lopera6b68322004-08-26 00:05:43 +0000176 Empty source string (which should never appear in real examples)
177 >>> e = doctest.Example('', '')
178 >>> e.source, e.want
179 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000180
Edward Lopera6b68322004-08-26 00:05:43 +0000181The constructor normalizes the `want` string to end in a newline,
182unless it's the empty string:
183
184 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000185 >>> e.source, e.want
186 ('print 1\n', '1\n')
187
Edward Lopera6b68322004-08-26 00:05:43 +0000188 >>> e = doctest.Example('print 1', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000189 >>> e.source, e.want
190 ('print 1\n', '1\n')
191
Edward Lopera6b68322004-08-26 00:05:43 +0000192 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000193 >>> e.source, e.want
194 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000195
196The constructor normalizes the `exc_msg` string to end in a newline,
197unless it's `None`:
198
199 Message spans one line
200 >>> exc_msg = 'IndexError: pop from an empty list'
201 >>> e = doctest.Example('[].pop()', '', exc_msg)
202 >>> e.exc_msg
203 'IndexError: pop from an empty list\n'
204
205 >>> exc_msg = 'IndexError: pop from an empty list\n'
206 >>> e = doctest.Example('[].pop()', '', exc_msg)
207 >>> e.exc_msg
208 'IndexError: pop from an empty list\n'
209
210 Message spans multiple lines
211 >>> exc_msg = 'ValueError: 1\n 2'
212 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
213 >>> e.exc_msg
214 'ValueError: 1\n 2\n'
215
216 >>> exc_msg = 'ValueError: 1\n 2\n'
217 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
218 >>> e.exc_msg
219 'ValueError: 1\n 2\n'
220
221 Empty (but non-None) exception message (which should never appear
222 in real examples)
223 >>> exc_msg = ''
224 >>> e = doctest.Example('raise X()', '', exc_msg)
225 >>> e.exc_msg
226 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000227"""
228
229def test_DocTest(): r"""
230Unit tests for the `DocTest` class.
231
232DocTest is a collection of examples, extracted from a docstring, along
233with information about where the docstring comes from (a name,
234filename, and line number). The docstring is parsed by the `DocTest`
235constructor:
236
237 >>> docstring = '''
238 ... >>> print 12
239 ... 12
240 ...
241 ... Non-example text.
242 ...
243 ... >>> print 'another\example'
244 ... another
245 ... example
246 ... '''
247 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000248 >>> parser = doctest.DocTestParser()
249 >>> test = parser.get_doctest(docstring, globs, 'some_test',
250 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000251 >>> print test
252 <DocTest some_test from some_file:20 (2 examples)>
253 >>> len(test.examples)
254 2
255 >>> e1, e2 = test.examples
256 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000257 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000258 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000259 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000260
261Source information (name, filename, and line number) is available as
262attributes on the doctest object:
263
264 >>> (test.name, test.filename, test.lineno)
265 ('some_test', 'some_file', 20)
266
267The line number of an example within its containing file is found by
268adding the line number of the example and the line number of its
269containing test:
270
271 >>> test.lineno + e1.lineno
272 21
273 >>> test.lineno + e2.lineno
274 26
275
276If the docstring contains inconsistant leading whitespace in the
277expected output of an example, then `DocTest` will raise a ValueError:
278
279 >>> docstring = r'''
280 ... >>> print 'bad\nindentation'
281 ... bad
282 ... indentation
283 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000284 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000285 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000286 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000287
288If the docstring contains inconsistent leading whitespace on
289continuation lines, then `DocTest` will raise a ValueError:
290
291 >>> docstring = r'''
292 ... >>> print ('bad indentation',
293 ... ... 2)
294 ... ('bad', 'indentation')
295 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000296 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000297 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000298 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
Tim Peters8485b562004-08-04 18:46:34 +0000299
300If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
301will raise a ValueError:
302
303 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000304 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000305 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000306 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
307
308If there's no blank space after a PS2 prompt ('...'), then `DocTest`
309will raise a ValueError:
310
311 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000312 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000313 Traceback (most recent call last):
314 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
315
Tim Peters8485b562004-08-04 18:46:34 +0000316"""
317
Tim Peters8485b562004-08-04 18:46:34 +0000318def test_DocTestFinder(): r"""
319Unit tests for the `DocTestFinder` class.
320
321DocTestFinder is used to extract DocTests from an object's docstring
322and the docstrings of its contained objects. It can be used with
323modules, functions, classes, methods, staticmethods, classmethods, and
324properties.
325
326Finding Tests in Functions
327~~~~~~~~~~~~~~~~~~~~~~~~~~
328For a function whose docstring contains examples, DocTestFinder.find()
329will return a single test (for that function's docstring):
330
Tim Peters8485b562004-08-04 18:46:34 +0000331 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000332
333We'll simulate a __file__ attr that ends in pyc:
334
335 >>> import test.test_doctest
336 >>> old = test.test_doctest.__file__
337 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
338
Tim Peters8485b562004-08-04 18:46:34 +0000339 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000340
Edward Loper74bca7a2004-08-12 02:27:44 +0000341 >>> print tests # doctest: +ELLIPSIS
Tim Petersa7def722004-08-23 22:13:22 +0000342 [<DocTest sample_func from ...:13 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000343
Tim Peters4de7c5c2004-08-23 22:38:05 +0000344The exact name depends on how test_doctest was invoked, so allow for
345leading path components.
346
347 >>> tests[0].filename # doctest: +ELLIPSIS
348 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000349
350 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000351
Jim Fulton07a349c2004-08-22 14:10:00 +0000352
Tim Peters8485b562004-08-04 18:46:34 +0000353 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000354 >>> (e.source, e.want, e.lineno)
355 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000356
Tim Peters8485b562004-08-04 18:46:34 +0000357If an object has no docstring, then a test is not created for it:
358
359 >>> def no_docstring(v):
360 ... pass
361 >>> finder.find(no_docstring)
362 []
363
364If the function has a docstring with no examples, then a test with no
365examples is returned. (This lets `DocTestRunner` collect statistics
366about which functions have no tests -- but is that useful? And should
367an empty test also be created when there's no docstring?)
368
369 >>> def no_examples(v):
370 ... ''' no doctest examples '''
371 >>> finder.find(no_examples)
372 [<DocTest no_examples from None:1 (no examples)>]
373
374Finding Tests in Classes
375~~~~~~~~~~~~~~~~~~~~~~~~
376For a class, DocTestFinder will create a test for the class's
377docstring, and will recursively explore its contents, including
378methods, classmethods, staticmethods, properties, and nested classes.
379
380 >>> finder = doctest.DocTestFinder()
381 >>> tests = finder.find(SampleClass)
382 >>> tests.sort()
383 >>> for t in tests:
384 ... print '%2s %s' % (len(t.examples), t.name)
385 1 SampleClass
386 3 SampleClass.NestedClass
387 1 SampleClass.NestedClass.__init__
388 1 SampleClass.__init__
389 2 SampleClass.a_classmethod
390 1 SampleClass.a_property
391 1 SampleClass.a_staticmethod
392 1 SampleClass.double
393 1 SampleClass.get
394
395New-style classes are also supported:
396
397 >>> tests = finder.find(SampleNewStyleClass)
398 >>> tests.sort()
399 >>> for t in tests:
400 ... print '%2s %s' % (len(t.examples), t.name)
401 1 SampleNewStyleClass
402 1 SampleNewStyleClass.__init__
403 1 SampleNewStyleClass.double
404 1 SampleNewStyleClass.get
405
406Finding Tests in Modules
407~~~~~~~~~~~~~~~~~~~~~~~~
408For a module, DocTestFinder will create a test for the class's
409docstring, and will recursively explore its contents, including
410functions, classes, and the `__test__` dictionary, if it exists:
411
412 >>> # A module
413 >>> import new
414 >>> m = new.module('some_module')
415 >>> def triple(val):
416 ... '''
417 ... >>> print tripple(11)
418 ... 33
419 ... '''
420 ... return val*3
421 >>> m.__dict__.update({
422 ... 'sample_func': sample_func,
423 ... 'SampleClass': SampleClass,
424 ... '__doc__': '''
425 ... Module docstring.
426 ... >>> print 'module'
427 ... module
428 ... ''',
429 ... '__test__': {
430 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
431 ... 'c': triple}})
432
433 >>> finder = doctest.DocTestFinder()
434 >>> # Use module=test.test_doctest, to prevent doctest from
435 >>> # ignoring the objects since they weren't defined in m.
436 >>> import test.test_doctest
437 >>> tests = finder.find(m, module=test.test_doctest)
438 >>> tests.sort()
439 >>> for t in tests:
440 ... print '%2s %s' % (len(t.examples), t.name)
441 1 some_module
442 1 some_module.SampleClass
443 3 some_module.SampleClass.NestedClass
444 1 some_module.SampleClass.NestedClass.__init__
445 1 some_module.SampleClass.__init__
446 2 some_module.SampleClass.a_classmethod
447 1 some_module.SampleClass.a_property
448 1 some_module.SampleClass.a_staticmethod
449 1 some_module.SampleClass.double
450 1 some_module.SampleClass.get
451 1 some_module.c
452 2 some_module.d
453 1 some_module.sample_func
454
455Duplicate Removal
456~~~~~~~~~~~~~~~~~
457If a single object is listed twice (under different names), then tests
458will only be generated for it once:
459
Tim Petersf3f57472004-08-08 06:11:48 +0000460 >>> from test import doctest_aliases
461 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000462 >>> tests.sort()
463 >>> print len(tests)
464 2
465 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000466 test.doctest_aliases.TwoNames
467
468 TwoNames.f and TwoNames.g are bound to the same object.
469 We can't guess which will be found in doctest's traversal of
470 TwoNames.__dict__ first, so we have to allow for either.
471
472 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000473 True
474
475Filter Functions
476~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000477A filter function can be used to restrict which objects get examined,
478but this is temporary, undocumented internal support for testmod's
479deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000480
481 >>> def namefilter(prefix, base):
482 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000483 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000484 >>> tests.sort()
485 >>> for t in tests:
486 ... print '%2s %s' % (len(t.examples), t.name)
487 1 SampleClass
488 3 SampleClass.NestedClass
489 1 SampleClass.NestedClass.__init__
490 1 SampleClass.__init__
491 1 SampleClass.double
492 1 SampleClass.get
493
Tim Peters8485b562004-08-04 18:46:34 +0000494If a given object is filtered out, then none of the objects that it
495contains will be added either:
496
497 >>> def namefilter(prefix, base):
498 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000499 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000500 >>> tests.sort()
501 >>> for t in tests:
502 ... print '%2s %s' % (len(t.examples), t.name)
503 1 SampleClass
504 1 SampleClass.__init__
505 2 SampleClass.a_classmethod
506 1 SampleClass.a_property
507 1 SampleClass.a_staticmethod
508 1 SampleClass.double
509 1 SampleClass.get
510
Tim Petersf727c6c2004-08-08 01:48:59 +0000511The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000512object explicitly passed to DocTestFinder:
513
514 >>> def namefilter(prefix, base):
515 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000516 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000517 >>> len(tests)
518 9
519
520Turning off Recursion
521~~~~~~~~~~~~~~~~~~~~~
522DocTestFinder can be told not to look for tests in contained objects
523using the `recurse` flag:
524
525 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
526 >>> tests.sort()
527 >>> for t in tests:
528 ... print '%2s %s' % (len(t.examples), t.name)
529 1 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000530
531Line numbers
532~~~~~~~~~~~~
533DocTestFinder finds the line number of each example:
534
535 >>> def f(x):
536 ... '''
537 ... >>> x = 12
538 ...
539 ... some text
540 ...
541 ... >>> # examples are not created for comments & bare prompts.
542 ... >>>
543 ... ...
544 ...
545 ... >>> for x in range(10):
546 ... ... print x,
547 ... 0 1 2 3 4 5 6 7 8 9
548 ... >>> x/2
549 ... 6
550 ... '''
551 >>> test = doctest.DocTestFinder().find(f)[0]
552 >>> [e.lineno for e in test.examples]
553 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000554"""
555
Edward Loper00f8da72004-08-26 18:05:07 +0000556def test_DocTestParser(): r"""
557Unit tests for the `DocTestParser` class.
558
559DocTestParser is used to parse docstrings containing doctest examples.
560
561The `parse` method divides a docstring into examples and intervening
562text:
563
564 >>> s = '''
565 ... >>> x, y = 2, 3 # no output expected
566 ... >>> if 1:
567 ... ... print x
568 ... ... print y
569 ... 2
570 ... 3
571 ...
572 ... Some text.
573 ... >>> x+y
574 ... 5
575 ... '''
576 >>> parser = doctest.DocTestParser()
577 >>> for piece in parser.parse(s):
578 ... if isinstance(piece, doctest.Example):
579 ... print 'Example:', (piece.source, piece.want, piece.lineno)
580 ... else:
581 ... print ' Text:', `piece`
582 Text: '\n'
583 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
584 Text: ''
585 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
586 Text: '\nSome text.\n'
587 Example: ('x+y\n', '5\n', 9)
588 Text: ''
589
590The `get_examples` method returns just the examples:
591
592 >>> for piece in parser.get_examples(s):
593 ... print (piece.source, piece.want, piece.lineno)
594 ('x, y = 2, 3 # no output expected\n', '', 1)
595 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
596 ('x+y\n', '5\n', 9)
597
598The `get_doctest` method creates a Test from the examples, along with the
599given arguments:
600
601 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
602 >>> (test.name, test.filename, test.lineno)
603 ('name', 'filename', 5)
604 >>> for piece in test.examples:
605 ... print (piece.source, piece.want, piece.lineno)
606 ('x, y = 2, 3 # no output expected\n', '', 1)
607 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
608 ('x+y\n', '5\n', 9)
609"""
610
Tim Peters8485b562004-08-04 18:46:34 +0000611class test_DocTestRunner:
612 def basics(): r"""
613Unit tests for the `DocTestRunner` class.
614
615DocTestRunner is used to run DocTest test cases, and to accumulate
616statistics. Here's a simple DocTest case we can use:
617
618 >>> def f(x):
619 ... '''
620 ... >>> x = 12
621 ... >>> print x
622 ... 12
623 ... >>> x/2
624 ... 6
625 ... '''
626 >>> test = doctest.DocTestFinder().find(f)[0]
627
628The main DocTestRunner interface is the `run` method, which runs a
629given DocTest case in a given namespace (globs). It returns a tuple
630`(f,t)`, where `f` is the number of failed tests and `t` is the number
631of tried tests.
632
633 >>> doctest.DocTestRunner(verbose=False).run(test)
634 (0, 3)
635
636If any example produces incorrect output, then the test runner reports
637the failure and proceeds to the next example:
638
639 >>> def f(x):
640 ... '''
641 ... >>> x = 12
642 ... >>> print x
643 ... 14
644 ... >>> x/2
645 ... 6
646 ... '''
647 >>> test = doctest.DocTestFinder().find(f)[0]
648 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000649 Trying:
650 x = 12
651 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000652 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000653 Trying:
654 print x
655 Expecting:
656 14
Tim Peters8485b562004-08-04 18:46:34 +0000657 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000658 Line 3, in f
659 Failed example:
660 print x
661 Expected:
662 14
663 Got:
664 12
Edward Loperaacf0832004-08-26 01:19:50 +0000665 Trying:
666 x/2
667 Expecting:
668 6
Tim Peters8485b562004-08-04 18:46:34 +0000669 ok
670 (1, 3)
671"""
672 def verbose_flag(): r"""
673The `verbose` flag makes the test runner generate more detailed
674output:
675
676 >>> def f(x):
677 ... '''
678 ... >>> x = 12
679 ... >>> print x
680 ... 12
681 ... >>> x/2
682 ... 6
683 ... '''
684 >>> test = doctest.DocTestFinder().find(f)[0]
685
686 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000687 Trying:
688 x = 12
689 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000690 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000691 Trying:
692 print x
693 Expecting:
694 12
Tim Peters8485b562004-08-04 18:46:34 +0000695 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000696 Trying:
697 x/2
698 Expecting:
699 6
Tim Peters8485b562004-08-04 18:46:34 +0000700 ok
701 (0, 3)
702
703If the `verbose` flag is unspecified, then the output will be verbose
704iff `-v` appears in sys.argv:
705
706 >>> # Save the real sys.argv list.
707 >>> old_argv = sys.argv
708
709 >>> # If -v does not appear in sys.argv, then output isn't verbose.
710 >>> sys.argv = ['test']
711 >>> doctest.DocTestRunner().run(test)
712 (0, 3)
713
714 >>> # If -v does appear in sys.argv, then output is verbose.
715 >>> sys.argv = ['test', '-v']
716 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000717 Trying:
718 x = 12
719 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000720 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000721 Trying:
722 print x
723 Expecting:
724 12
Tim Peters8485b562004-08-04 18:46:34 +0000725 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000726 Trying:
727 x/2
728 Expecting:
729 6
Tim Peters8485b562004-08-04 18:46:34 +0000730 ok
731 (0, 3)
732
733 >>> # Restore sys.argv
734 >>> sys.argv = old_argv
735
736In the remaining examples, the test runner's verbosity will be
737explicitly set, to ensure that the test behavior is consistent.
738 """
739 def exceptions(): r"""
740Tests of `DocTestRunner`'s exception handling.
741
742An expected exception is specified with a traceback message. The
743lines between the first line and the type/value may be omitted or
744replaced with any other string:
745
746 >>> def f(x):
747 ... '''
748 ... >>> x = 12
749 ... >>> print x/0
750 ... Traceback (most recent call last):
751 ... ZeroDivisionError: integer division or modulo by zero
752 ... '''
753 >>> test = doctest.DocTestFinder().find(f)[0]
754 >>> doctest.DocTestRunner(verbose=False).run(test)
755 (0, 2)
756
Edward Loper19b19582004-08-25 23:07:03 +0000757An example may not generate output before it raises an exception; if
758it does, then the traceback message will not be recognized as
759signaling an expected exception, so the example will be reported as an
760unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000761
762 >>> def f(x):
763 ... '''
764 ... >>> x = 12
765 ... >>> print 'pre-exception output', x/0
766 ... pre-exception output
767 ... Traceback (most recent call last):
768 ... ZeroDivisionError: integer division or modulo by zero
769 ... '''
770 >>> test = doctest.DocTestFinder().find(f)[0]
771 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000772 ... # doctest: +ELLIPSIS
773 **********************************************************************
774 Line 3, in f
775 Failed example:
776 print 'pre-exception output', x/0
777 Exception raised:
778 ...
779 ZeroDivisionError: integer division or modulo by zero
780 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000781
782Exception messages may contain newlines:
783
784 >>> def f(x):
785 ... r'''
786 ... >>> raise ValueError, 'multi\nline\nmessage'
787 ... Traceback (most recent call last):
788 ... ValueError: multi
789 ... line
790 ... message
791 ... '''
792 >>> test = doctest.DocTestFinder().find(f)[0]
793 >>> doctest.DocTestRunner(verbose=False).run(test)
794 (0, 1)
795
796If an exception is expected, but an exception with the wrong type or
797message is raised, then it is reported as a failure:
798
799 >>> def f(x):
800 ... r'''
801 ... >>> raise ValueError, 'message'
802 ... Traceback (most recent call last):
803 ... ValueError: wrong message
804 ... '''
805 >>> test = doctest.DocTestFinder().find(f)[0]
806 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000807 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000808 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000809 Line 2, in f
810 Failed example:
811 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000812 Expected:
813 Traceback (most recent call last):
814 ValueError: wrong message
815 Got:
816 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000817 ...
Tim Peters8485b562004-08-04 18:46:34 +0000818 ValueError: message
819 (1, 1)
820
821If an exception is raised but not expected, then it is reported as an
822unexpected exception:
823
Tim Peters8485b562004-08-04 18:46:34 +0000824 >>> def f(x):
825 ... r'''
826 ... >>> 1/0
827 ... 0
828 ... '''
829 >>> test = doctest.DocTestFinder().find(f)[0]
830 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000831 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000832 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000833 Line 2, in f
834 Failed example:
835 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000836 Exception raised:
837 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000838 ...
Tim Peters8485b562004-08-04 18:46:34 +0000839 ZeroDivisionError: integer division or modulo by zero
840 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000841"""
842 def optionflags(): r"""
843Tests of `DocTestRunner`'s option flag handling.
844
845Several option flags can be used to customize the behavior of the test
846runner. These are defined as module constants in doctest, and passed
847to the DocTestRunner constructor (multiple constants should be or-ed
848together).
849
850The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
851and 1/0:
852
853 >>> def f(x):
854 ... '>>> True\n1\n'
855
856 >>> # Without the flag:
857 >>> test = doctest.DocTestFinder().find(f)[0]
858 >>> doctest.DocTestRunner(verbose=False).run(test)
859 (0, 1)
860
861 >>> # With the flag:
862 >>> test = doctest.DocTestFinder().find(f)[0]
863 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
864 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
865 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000866 Line 1, in f
867 Failed example:
868 True
869 Expected:
870 1
871 Got:
872 True
Tim Peters8485b562004-08-04 18:46:34 +0000873 (1, 1)
874
875The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
876and the '<BLANKLINE>' marker:
877
878 >>> def f(x):
879 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
880
881 >>> # Without the flag:
882 >>> test = doctest.DocTestFinder().find(f)[0]
883 >>> doctest.DocTestRunner(verbose=False).run(test)
884 (0, 1)
885
886 >>> # With the flag:
887 >>> test = doctest.DocTestFinder().find(f)[0]
888 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
889 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
890 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000891 Line 1, in f
892 Failed example:
893 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000894 Expected:
895 a
896 <BLANKLINE>
897 b
898 Got:
899 a
900 <BLANKLINE>
901 b
902 (1, 1)
903
904The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
905treated as equal:
906
907 >>> def f(x):
908 ... '>>> print 1, 2, 3\n 1 2\n 3'
909
910 >>> # Without the flag:
911 >>> test = doctest.DocTestFinder().find(f)[0]
912 >>> doctest.DocTestRunner(verbose=False).run(test)
913 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000914 Line 1, in f
915 Failed example:
916 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000917 Expected:
918 1 2
919 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000920 Got:
921 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000922 (1, 1)
923
924 >>> # With the flag:
925 >>> test = doctest.DocTestFinder().find(f)[0]
926 >>> flags = doctest.NORMALIZE_WHITESPACE
927 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
928 (0, 1)
929
Tim Peters026f8dc2004-08-19 16:38:58 +0000930 An example from the docs:
931 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
932 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
933 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
934
Tim Peters8485b562004-08-04 18:46:34 +0000935The ELLIPSIS flag causes ellipsis marker ("...") in the expected
936output to match any substring in the actual output:
937
938 >>> def f(x):
939 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
940
941 >>> # Without the flag:
942 >>> test = doctest.DocTestFinder().find(f)[0]
943 >>> doctest.DocTestRunner(verbose=False).run(test)
944 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000945 Line 1, in f
946 Failed example:
947 print range(15)
948 Expected:
949 [0, 1, 2, ..., 14]
950 Got:
951 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +0000952 (1, 1)
953
954 >>> # With the flag:
955 >>> test = doctest.DocTestFinder().find(f)[0]
956 >>> flags = doctest.ELLIPSIS
957 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
958 (0, 1)
959
Tim Peterse594bee2004-08-22 01:47:51 +0000960 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +0000961
962 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +0000963 ... print i**2, #doctest: +ELLIPSIS
964 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +0000965
Tim Peters026f8dc2004-08-19 16:38:58 +0000966 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000967
968 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +0000969 ... print i,
970 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +0000971
Tim Peters026f8dc2004-08-19 16:38:58 +0000972 Examples from the docs:
973
974 >>> print range(20) # doctest:+ELLIPSIS
975 [0, 1, ..., 18, 19]
976
977 >>> print range(20) # doctest: +ELLIPSIS
978 ... # doctest: +NORMALIZE_WHITESPACE
979 [0, 1, ..., 18, 19]
980
Edward Loper71f55af2004-08-26 01:41:51 +0000981The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +0000982and actual outputs to be displayed using a unified diff:
983
984 >>> def f(x):
985 ... r'''
986 ... >>> print '\n'.join('abcdefg')
987 ... a
988 ... B
989 ... c
990 ... d
991 ... f
992 ... g
993 ... h
994 ... '''
995
996 >>> # Without the flag:
997 >>> test = doctest.DocTestFinder().find(f)[0]
998 >>> doctest.DocTestRunner(verbose=False).run(test)
999 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001000 Line 2, in f
1001 Failed example:
1002 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001003 Expected:
1004 a
1005 B
1006 c
1007 d
1008 f
1009 g
1010 h
1011 Got:
1012 a
1013 b
1014 c
1015 d
1016 e
1017 f
1018 g
1019 (1, 1)
1020
1021 >>> # With the flag:
1022 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001023 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001024 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1025 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001026 Line 2, in f
1027 Failed example:
1028 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001029 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001030 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001031 a
1032 -B
1033 +b
1034 c
1035 d
1036 +e
1037 f
1038 g
1039 -h
Tim Peters8485b562004-08-04 18:46:34 +00001040 (1, 1)
1041
Edward Loper71f55af2004-08-26 01:41:51 +00001042The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001043and actual outputs to be displayed using a context diff:
1044
Edward Loper71f55af2004-08-26 01:41:51 +00001045 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001046 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001047 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001048 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1049 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001050 Line 2, in f
1051 Failed example:
1052 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001053 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001054 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001055 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001056 a
1057 ! B
1058 c
1059 d
1060 f
1061 g
1062 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001063 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001064 a
1065 ! b
1066 c
1067 d
1068 + e
1069 f
1070 g
Tim Peters8485b562004-08-04 18:46:34 +00001071 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001072
1073
Edward Loper71f55af2004-08-26 01:41:51 +00001074The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001075used by the popular ndiff.py utility. This does intraline difference
1076marking, as well as interline differences.
1077
1078 >>> def f(x):
1079 ... r'''
1080 ... >>> print "a b c d e f g h i j k l m"
1081 ... a b c d e f g h i j k 1 m
1082 ... '''
1083 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001084 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001085 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1086 **********************************************************************
1087 Line 2, in f
1088 Failed example:
1089 print "a b c d e f g h i j k l m"
1090 Differences (ndiff with -expected +actual):
1091 - a b c d e f g h i j k 1 m
1092 ? ^
1093 + a b c d e f g h i j k l m
1094 ? + ++ ^
Tim Petersc6cbab02004-08-22 19:43:28 +00001095 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001096
1097The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1098failing example:
1099
1100 >>> def f(x):
1101 ... r'''
1102 ... >>> print 1 # first success
1103 ... 1
1104 ... >>> print 2 # first failure
1105 ... 200
1106 ... >>> print 3 # second failure
1107 ... 300
1108 ... >>> print 4 # second success
1109 ... 4
1110 ... >>> print 5 # third failure
1111 ... 500
1112 ... '''
1113 >>> test = doctest.DocTestFinder().find(f)[0]
1114 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1115 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1116 **********************************************************************
1117 Line 4, in f
1118 Failed example:
1119 print 2 # first failure
1120 Expected:
1121 200
1122 Got:
1123 2
1124 (3, 5)
1125
1126However, output from `report_start` is not supressed:
1127
1128 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
1129 Trying:
1130 print 1 # first success
1131 Expecting:
1132 1
1133 ok
1134 Trying:
1135 print 2 # first failure
1136 Expecting:
1137 200
1138 **********************************************************************
1139 Line 4, in f
1140 Failed example:
1141 print 2 # first failure
1142 Expected:
1143 200
1144 Got:
1145 2
1146 (3, 5)
1147
1148For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1149count as failures:
1150
1151 >>> def f(x):
1152 ... r'''
1153 ... >>> print 1 # first success
1154 ... 1
1155 ... >>> raise ValueError(2) # first failure
1156 ... 200
1157 ... >>> print 3 # second failure
1158 ... 300
1159 ... >>> print 4 # second success
1160 ... 4
1161 ... >>> print 5 # third failure
1162 ... 500
1163 ... '''
1164 >>> test = doctest.DocTestFinder().find(f)[0]
1165 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1166 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1167 ... # doctest: +ELLIPSIS
1168 **********************************************************************
1169 Line 4, in f
1170 Failed example:
1171 raise ValueError(2) # first failure
1172 Exception raised:
1173 ...
1174 ValueError: 2
1175 (3, 5)
1176
Tim Petersc6cbab02004-08-22 19:43:28 +00001177 """
1178
Tim Peters8485b562004-08-04 18:46:34 +00001179 def option_directives(): r"""
1180Tests of `DocTestRunner`'s option directive mechanism.
1181
Edward Loper74bca7a2004-08-12 02:27:44 +00001182Option directives can be used to turn option flags on or off for a
1183single example. To turn an option on for an example, follow that
1184example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001185
1186 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001187 ... >>> print range(10) # should fail: no ellipsis
1188 ... [0, 1, ..., 9]
1189 ...
1190 ... >>> print range(10) # doctest: +ELLIPSIS
1191 ... [0, 1, ..., 9]
1192 ... '''
1193 >>> test = doctest.DocTestFinder().find(f)[0]
1194 >>> doctest.DocTestRunner(verbose=False).run(test)
1195 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001196 Line 2, in f
1197 Failed example:
1198 print range(10) # should fail: no ellipsis
1199 Expected:
1200 [0, 1, ..., 9]
1201 Got:
1202 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001203 (1, 2)
1204
1205To turn an option off for an example, follow that example with a
1206comment of the form ``# doctest: -OPTION``:
1207
1208 >>> def f(x): r'''
1209 ... >>> print range(10)
1210 ... [0, 1, ..., 9]
1211 ...
1212 ... >>> # should fail: no ellipsis
1213 ... >>> print range(10) # doctest: -ELLIPSIS
1214 ... [0, 1, ..., 9]
1215 ... '''
1216 >>> test = doctest.DocTestFinder().find(f)[0]
1217 >>> doctest.DocTestRunner(verbose=False,
1218 ... optionflags=doctest.ELLIPSIS).run(test)
1219 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001220 Line 6, in f
1221 Failed example:
1222 print range(10) # doctest: -ELLIPSIS
1223 Expected:
1224 [0, 1, ..., 9]
1225 Got:
1226 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001227 (1, 2)
1228
1229Option directives affect only the example that they appear with; they
1230do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001231
Edward Loper74bca7a2004-08-12 02:27:44 +00001232 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001233 ... >>> print range(10) # Should fail: no ellipsis
1234 ... [0, 1, ..., 9]
1235 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001236 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001237 ... [0, 1, ..., 9]
1238 ...
Tim Peters8485b562004-08-04 18:46:34 +00001239 ... >>> print range(10) # Should fail: no ellipsis
1240 ... [0, 1, ..., 9]
1241 ... '''
1242 >>> test = doctest.DocTestFinder().find(f)[0]
1243 >>> doctest.DocTestRunner(verbose=False).run(test)
1244 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001245 Line 2, in f
1246 Failed example:
1247 print range(10) # Should fail: no ellipsis
1248 Expected:
1249 [0, 1, ..., 9]
1250 Got:
1251 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001252 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001253 Line 8, in f
1254 Failed example:
1255 print range(10) # Should fail: no ellipsis
1256 Expected:
1257 [0, 1, ..., 9]
1258 Got:
1259 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001260 (2, 3)
1261
Edward Loper74bca7a2004-08-12 02:27:44 +00001262Multiple options may be modified by a single option directive. They
1263may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001264
1265 >>> def f(x): r'''
1266 ... >>> print range(10) # Should fail
1267 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001268 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001269 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001270 ... [0, 1, ..., 9]
1271 ... '''
1272 >>> test = doctest.DocTestFinder().find(f)[0]
1273 >>> doctest.DocTestRunner(verbose=False).run(test)
1274 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001275 Line 2, in f
1276 Failed example:
1277 print range(10) # Should fail
1278 Expected:
1279 [0, 1, ..., 9]
1280 Got:
1281 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001282 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001283
1284 >>> def f(x): r'''
1285 ... >>> print range(10) # Should fail
1286 ... [0, 1, ..., 9]
1287 ... >>> print range(10) # Should succeed
1288 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1289 ... [0, 1, ..., 9]
1290 ... '''
1291 >>> test = doctest.DocTestFinder().find(f)[0]
1292 >>> doctest.DocTestRunner(verbose=False).run(test)
1293 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001294 Line 2, in f
1295 Failed example:
1296 print range(10) # Should fail
1297 Expected:
1298 [0, 1, ..., 9]
1299 Got:
1300 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001301 (1, 2)
1302
1303 >>> def f(x): r'''
1304 ... >>> print range(10) # Should fail
1305 ... [0, 1, ..., 9]
1306 ... >>> print range(10) # Should succeed
1307 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1308 ... [0, 1, ..., 9]
1309 ... '''
1310 >>> test = doctest.DocTestFinder().find(f)[0]
1311 >>> doctest.DocTestRunner(verbose=False).run(test)
1312 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001313 Line 2, in f
1314 Failed example:
1315 print range(10) # Should fail
1316 Expected:
1317 [0, 1, ..., 9]
1318 Got:
1319 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001320 (1, 2)
1321
1322The option directive may be put on the line following the source, as
1323long as a continuation prompt is used:
1324
1325 >>> def f(x): r'''
1326 ... >>> print range(10)
1327 ... ... # doctest: +ELLIPSIS
1328 ... [0, 1, ..., 9]
1329 ... '''
1330 >>> test = doctest.DocTestFinder().find(f)[0]
1331 >>> doctest.DocTestRunner(verbose=False).run(test)
1332 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001333
Edward Loper74bca7a2004-08-12 02:27:44 +00001334For examples with multi-line source, the option directive may appear
1335at the end of any line:
1336
1337 >>> def f(x): r'''
1338 ... >>> for x in range(10): # doctest: +ELLIPSIS
1339 ... ... print x,
1340 ... 0 1 2 ... 9
1341 ...
1342 ... >>> for x in range(10):
1343 ... ... print x, # doctest: +ELLIPSIS
1344 ... 0 1 2 ... 9
1345 ... '''
1346 >>> test = doctest.DocTestFinder().find(f)[0]
1347 >>> doctest.DocTestRunner(verbose=False).run(test)
1348 (0, 2)
1349
1350If more than one line of an example with multi-line source has an
1351option directive, then they are combined:
1352
1353 >>> def f(x): r'''
1354 ... Should fail (option directive not on the last line):
1355 ... >>> for x in range(10): # doctest: +ELLIPSIS
1356 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1357 ... 0 1 2...9
1358 ... '''
1359 >>> test = doctest.DocTestFinder().find(f)[0]
1360 >>> doctest.DocTestRunner(verbose=False).run(test)
1361 (0, 1)
1362
1363It is an error to have a comment of the form ``# doctest:`` that is
1364*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1365``OPTION`` is an option that has been registered with
1366`register_option`:
1367
1368 >>> # Error: Option not registered
1369 >>> s = '>>> print 12 #doctest: +BADOPTION'
1370 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1371 Traceback (most recent call last):
1372 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1373
1374 >>> # Error: No + or - prefix
1375 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1376 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1377 Traceback (most recent call last):
1378 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1379
1380It is an error to use an option directive on a line that contains no
1381source:
1382
1383 >>> s = '>>> # doctest: +ELLIPSIS'
1384 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1385 Traceback (most recent call last):
1386 ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
Tim Peters8485b562004-08-04 18:46:34 +00001387"""
1388
1389def test_testsource(): r"""
1390Unit tests for `testsource()`.
1391
1392The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001393test with that name in that module, and converts it to a script. The
1394example code is converted to regular Python code. The surrounding
1395words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001396
1397 >>> import test.test_doctest
1398 >>> name = 'test.test_doctest.sample_func'
1399 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001400 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001401 #
Tim Peters8485b562004-08-04 18:46:34 +00001402 print sample_func(22)
1403 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001404 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001405 #
Edward Lopera5db6002004-08-12 02:41:30 +00001406 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001407
1408 >>> name = 'test.test_doctest.SampleNewStyleClass'
1409 >>> print doctest.testsource(test.test_doctest, name)
1410 print '1\n2\n3'
1411 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001412 ## 1
1413 ## 2
1414 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001415
1416 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1417 >>> print doctest.testsource(test.test_doctest, name)
1418 print SampleClass.a_classmethod(10)
1419 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001420 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001421 print SampleClass(0).a_classmethod(10)
1422 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001423 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001424"""
1425
1426def test_debug(): r"""
1427
1428Create a docstring that we want to debug:
1429
1430 >>> s = '''
1431 ... >>> x = 12
1432 ... >>> print x
1433 ... 12
1434 ... '''
1435
1436Create some fake stdin input, to feed to the debugger:
1437
1438 >>> import tempfile
1439 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1440 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1441 >>> fake_stdin.seek(0)
1442 >>> real_stdin = sys.stdin
1443 >>> sys.stdin = fake_stdin
1444
1445Run the debugger on the docstring, and then restore sys.stdin.
1446
Tim Peters8485b562004-08-04 18:46:34 +00001447 >>> try:
1448 ... doctest.debug_src(s)
1449 ... finally:
1450 ... sys.stdin = real_stdin
1451 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001452 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001453 > <string>(1)?()
1454 (Pdb) 12
1455 --Return--
1456 > <string>(1)?()->None
1457 (Pdb) 12
1458 (Pdb)
1459
1460"""
1461
Jim Fulton356fd192004-08-09 11:34:47 +00001462def test_pdb_set_trace():
1463 r"""Using pdb.set_trace from a doctest
1464
Tim Peters413ced62004-08-09 15:43:47 +00001465 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001466 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001467 you use it. The doctest module changes sys.stdout so that it can
1468 capture program output. It also temporarily replaces pdb.set_trace
1469 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001470 see debugger output.
1471
1472 >>> doc = '''
1473 ... >>> x = 42
1474 ... >>> import pdb; pdb.set_trace()
1475 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001476 >>> parser = doctest.DocTestParser()
1477 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001478 >>> runner = doctest.DocTestRunner(verbose=False)
1479
1480 To demonstrate this, we'll create a fake standard input that
1481 captures our debugger input:
1482
1483 >>> import tempfile
1484 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1485 >>> fake_stdin.write('\n'.join([
1486 ... 'up', # up out of pdb.set_trace
1487 ... 'up', # up again to get out of our wrapper
1488 ... 'print x', # print data defined by the example
1489 ... 'continue', # stop debugging
1490 ... '']))
1491 >>> fake_stdin.seek(0)
1492 >>> real_stdin = sys.stdin
1493 >>> sys.stdin = fake_stdin
1494
Edward Loper74bca7a2004-08-12 02:27:44 +00001495 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001496 --Return--
1497 > ...set_trace()->None
1498 -> Pdb().set_trace()
1499 (Pdb) > ...set_trace()
1500 -> real_pdb_set_trace()
1501 (Pdb) > <string>(1)?()
1502 (Pdb) 42
1503 (Pdb) (0, 2)
1504
1505 >>> sys.stdin = real_stdin
1506 >>> fake_stdin.close()
1507
1508 You can also put pdb.set_trace in a function called from a test:
1509
1510 >>> def calls_set_trace():
1511 ... y=2
1512 ... import pdb; pdb.set_trace()
1513
1514 >>> doc = '''
1515 ... >>> x=1
1516 ... >>> calls_set_trace()
1517 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001518 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001519 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1520 >>> fake_stdin.write('\n'.join([
1521 ... 'up', # up out of pdb.set_trace
1522 ... 'up', # up again to get out of our wrapper
1523 ... 'print y', # print data defined in the function
1524 ... 'up', # out of function
1525 ... 'print x', # print data defined by the example
1526 ... 'continue', # stop debugging
1527 ... '']))
1528 >>> fake_stdin.seek(0)
1529 >>> real_stdin = sys.stdin
1530 >>> sys.stdin = fake_stdin
1531
Edward Loper74bca7a2004-08-12 02:27:44 +00001532 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001533 --Return--
1534 > ...set_trace()->None
1535 -> Pdb().set_trace()
1536 (Pdb) ...set_trace()
1537 -> real_pdb_set_trace()
1538 (Pdb) > <string>(3)calls_set_trace()
1539 (Pdb) 2
1540 (Pdb) > <string>(1)?()
1541 (Pdb) 1
1542 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001543 """
1544
Tim Peters19397e52004-08-06 22:02:59 +00001545def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001546 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001547
1548 We create a Suite by providing a module. A module can be provided
1549 by passing a module object:
1550
1551 >>> import unittest
1552 >>> import test.sample_doctest
1553 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1554 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001555 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001556
1557 We can also supply the module by name:
1558
1559 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1560 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001561 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001562
1563 We can use the current module:
1564
1565 >>> suite = test.sample_doctest.test_suite()
1566 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001567 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001568
1569 We can supply global variables. If we pass globs, they will be
1570 used instead of the module globals. Here we'll pass an empty
1571 globals, triggering an extra error:
1572
1573 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1574 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001575 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001576
1577 Alternatively, we can provide extra globals. Here we'll make an
1578 error go away by providing an extra global variable:
1579
1580 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1581 ... extraglobs={'y': 1})
1582 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001583 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001584
1585 You can pass option flags. Here we'll cause an extra error
1586 by disabling the blank-line feature:
1587
1588 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001589 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001590 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001591 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001592
Tim Peters1e277ee2004-08-07 05:37:52 +00001593 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001594
1595 >>> def setUp():
1596 ... import test.test_doctest
1597 ... test.test_doctest.sillySetup = True
1598
1599 >>> def tearDown():
1600 ... import test.test_doctest
1601 ... del test.test_doctest.sillySetup
1602
1603 Here, we installed a silly variable that the test expects:
1604
1605 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1606 ... setUp=setUp, tearDown=tearDown)
1607 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001608 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001609
1610 But the tearDown restores sanity:
1611
1612 >>> import test.test_doctest
1613 >>> test.test_doctest.sillySetup
1614 Traceback (most recent call last):
1615 ...
1616 AttributeError: 'module' object has no attribute 'sillySetup'
1617
1618 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001619 use a custom test_finder to to run just the test named bar.
1620 However, the test in the module docstring, and the two tests
1621 in the module __test__ dict, aren't filtered, so we actually
1622 run three tests besides bar's. The filtering mechanisms are
1623 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001624
1625 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001626 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001627 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1628 ... test_finder=finder)
1629 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001630 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001631 """
1632
1633def test_DocFileSuite():
1634 """We can test tests found in text files using a DocFileSuite.
1635
1636 We create a suite by providing the names of one or more text
1637 files that include examples:
1638
1639 >>> import unittest
1640 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1641 ... 'test_doctest2.txt')
1642 >>> suite.run(unittest.TestResult())
1643 <unittest.TestResult run=2 errors=0 failures=2>
1644
1645 The test files are looked for in the directory containing the
1646 calling module. A package keyword argument can be provided to
1647 specify a different relative location.
1648
1649 >>> import unittest
1650 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1651 ... 'test_doctest2.txt',
1652 ... package='test')
1653 >>> suite.run(unittest.TestResult())
1654 <unittest.TestResult run=2 errors=0 failures=2>
1655
1656 Note that '/' should be used as a path separator. It will be
1657 converted to a native separator at run time:
1658
1659
1660 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1661 >>> suite.run(unittest.TestResult())
1662 <unittest.TestResult run=1 errors=0 failures=1>
1663
1664 You can specify initial global variables:
1665
1666 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1667 ... 'test_doctest2.txt',
1668 ... globs={'favorite_color': 'blue'})
1669 >>> suite.run(unittest.TestResult())
1670 <unittest.TestResult run=2 errors=0 failures=1>
1671
1672 In this case, we supplied a missing favorite color. You can
1673 provide doctest options:
1674
1675 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1676 ... 'test_doctest2.txt',
1677 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1678 ... globs={'favorite_color': 'blue'})
1679 >>> suite.run(unittest.TestResult())
1680 <unittest.TestResult run=2 errors=0 failures=2>
1681
1682 And, you can provide setUp and tearDown functions:
1683
1684 You can supply setUp and teatDoen functions:
1685
1686 >>> def setUp():
1687 ... import test.test_doctest
1688 ... test.test_doctest.sillySetup = True
1689
1690 >>> def tearDown():
1691 ... import test.test_doctest
1692 ... del test.test_doctest.sillySetup
1693
1694 Here, we installed a silly variable that the test expects:
1695
1696 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1697 ... 'test_doctest2.txt',
1698 ... setUp=setUp, tearDown=tearDown)
1699 >>> suite.run(unittest.TestResult())
1700 <unittest.TestResult run=2 errors=0 failures=1>
1701
1702 But the tearDown restores sanity:
1703
1704 >>> import test.test_doctest
1705 >>> test.test_doctest.sillySetup
1706 Traceback (most recent call last):
1707 ...
1708 AttributeError: 'module' object has no attribute 'sillySetup'
1709
1710 """
1711
Jim Fulton07a349c2004-08-22 14:10:00 +00001712def test_trailing_space_in_test():
1713 """
Tim Petersa7def722004-08-23 22:13:22 +00001714 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001715
Jim Fulton07a349c2004-08-22 14:10:00 +00001716 >>> x, y = 'foo', ''
1717 >>> print x, y
1718 foo \n
1719 """
Tim Peters19397e52004-08-06 22:02:59 +00001720
Tim Petersa7def722004-08-23 22:13:22 +00001721# old_test1, ... used to live in doctest.py, but cluttered it. Note
1722# that these use the deprecated doctest.Tester, so should go away (or
1723# be rewritten) someday.
1724
1725# Ignore all warnings about the use of class Tester in this module.
1726# Note that the name of this module may differ depending on how it's
1727# imported, so the use of __name__ is important.
1728warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1729 __name__, 0)
1730
1731def old_test1(): r"""
1732>>> from doctest import Tester
1733>>> t = Tester(globs={'x': 42}, verbose=0)
1734>>> t.runstring(r'''
1735... >>> x = x * 2
1736... >>> print x
1737... 42
1738... ''', 'XYZ')
1739**********************************************************************
1740Line 3, in XYZ
1741Failed example:
1742 print x
1743Expected:
1744 42
1745Got:
1746 84
1747(1, 2)
1748>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1749(0, 2)
1750>>> t.summarize()
1751**********************************************************************
17521 items had failures:
1753 1 of 2 in XYZ
1754***Test Failed*** 1 failures.
1755(1, 4)
1756>>> t.summarize(verbose=1)
17571 items passed all tests:
1758 2 tests in example2
1759**********************************************************************
17601 items had failures:
1761 1 of 2 in XYZ
17624 tests in 2 items.
17633 passed and 1 failed.
1764***Test Failed*** 1 failures.
1765(1, 4)
1766"""
1767
1768def old_test2(): r"""
1769 >>> from doctest import Tester
1770 >>> t = Tester(globs={}, verbose=1)
1771 >>> test = r'''
1772 ... # just an example
1773 ... >>> x = 1 + 2
1774 ... >>> x
1775 ... 3
1776 ... '''
1777 >>> t.runstring(test, "Example")
1778 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00001779 Trying:
1780 x = 1 + 2
1781 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00001782 ok
Edward Loperaacf0832004-08-26 01:19:50 +00001783 Trying:
1784 x
1785 Expecting:
1786 3
Tim Petersa7def722004-08-23 22:13:22 +00001787 ok
1788 0 of 2 examples failed in string Example
1789 (0, 2)
1790"""
1791
1792def old_test3(): r"""
1793 >>> from doctest import Tester
1794 >>> t = Tester(globs={}, verbose=0)
1795 >>> def _f():
1796 ... '''Trivial docstring example.
1797 ... >>> assert 2 == 2
1798 ... '''
1799 ... return 32
1800 ...
1801 >>> t.rundoc(_f) # expect 0 failures in 1 example
1802 (0, 1)
1803"""
1804
1805def old_test4(): """
1806 >>> import new
1807 >>> m1 = new.module('_m1')
1808 >>> m2 = new.module('_m2')
1809 >>> test_data = \"""
1810 ... def _f():
1811 ... '''>>> assert 1 == 1
1812 ... '''
1813 ... def g():
1814 ... '''>>> assert 2 != 1
1815 ... '''
1816 ... class H:
1817 ... '''>>> assert 2 > 1
1818 ... '''
1819 ... def bar(self):
1820 ... '''>>> assert 1 < 2
1821 ... '''
1822 ... \"""
1823 >>> exec test_data in m1.__dict__
1824 >>> exec test_data in m2.__dict__
1825 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
1826
1827 Tests that objects outside m1 are excluded:
1828
1829 >>> from doctest import Tester
1830 >>> t = Tester(globs={}, verbose=0)
1831 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
1832 (0, 4)
1833
1834 Once more, not excluding stuff outside m1:
1835
1836 >>> t = Tester(globs={}, verbose=0)
1837 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
1838 (0, 8)
1839
1840 The exclusion of objects from outside the designated module is
1841 meant to be invoked automagically by testmod.
1842
1843 >>> doctest.testmod(m1, verbose=False)
1844 (0, 4)
1845"""
1846
Tim Peters8485b562004-08-04 18:46:34 +00001847######################################################################
1848## Main
1849######################################################################
1850
1851def test_main():
1852 # Check the doctest cases in doctest itself:
1853 test_support.run_doctest(doctest, verbosity=True)
1854 # Check the doctest cases defined here:
1855 from test import test_doctest
1856 test_support.run_doctest(test_doctest, verbosity=True)
1857
1858import trace, sys, re, StringIO
1859def test_coverage(coverdir):
1860 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1861 trace=0, count=1)
1862 tracer.run('reload(doctest); test_main()')
1863 r = tracer.results()
1864 print 'Writing coverage results...'
1865 r.write_results(show_missing=True, summary=True,
1866 coverdir=coverdir)
1867
1868if __name__ == '__main__':
1869 if '-c' in sys.argv:
1870 test_coverage('/tmp/doctest.cover')
1871 else:
1872 test_main()