blob: 0f94fdf2a5b23bdd7d49ca47357a8f0e5953577d [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 Loper7c748462004-08-09 02:06:06 +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):
298 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: ' ... 2)'
299
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
556class test_DocTestRunner:
557 def basics(): r"""
558Unit tests for the `DocTestRunner` class.
559
560DocTestRunner is used to run DocTest test cases, and to accumulate
561statistics. Here's a simple DocTest case we can use:
562
563 >>> def f(x):
564 ... '''
565 ... >>> x = 12
566 ... >>> print x
567 ... 12
568 ... >>> x/2
569 ... 6
570 ... '''
571 >>> test = doctest.DocTestFinder().find(f)[0]
572
573The main DocTestRunner interface is the `run` method, which runs a
574given DocTest case in a given namespace (globs). It returns a tuple
575`(f,t)`, where `f` is the number of failed tests and `t` is the number
576of tried tests.
577
578 >>> doctest.DocTestRunner(verbose=False).run(test)
579 (0, 3)
580
581If any example produces incorrect output, then the test runner reports
582the failure and proceeds to the next example:
583
584 >>> def f(x):
585 ... '''
586 ... >>> x = 12
587 ... >>> print x
588 ... 14
589 ... >>> x/2
590 ... 6
591 ... '''
592 >>> test = doctest.DocTestFinder().find(f)[0]
593 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000594 Trying:
595 x = 12
596 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000597 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000598 Trying:
599 print x
600 Expecting:
601 14
Tim Peters8485b562004-08-04 18:46:34 +0000602 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000603 Line 3, in f
604 Failed example:
605 print x
606 Expected:
607 14
608 Got:
609 12
Edward Loperaacf0832004-08-26 01:19:50 +0000610 Trying:
611 x/2
612 Expecting:
613 6
Tim Peters8485b562004-08-04 18:46:34 +0000614 ok
615 (1, 3)
616"""
617 def verbose_flag(): r"""
618The `verbose` flag makes the test runner generate more detailed
619output:
620
621 >>> def f(x):
622 ... '''
623 ... >>> x = 12
624 ... >>> print x
625 ... 12
626 ... >>> x/2
627 ... 6
628 ... '''
629 >>> test = doctest.DocTestFinder().find(f)[0]
630
631 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000632 Trying:
633 x = 12
634 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000635 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000636 Trying:
637 print x
638 Expecting:
639 12
Tim Peters8485b562004-08-04 18:46:34 +0000640 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000641 Trying:
642 x/2
643 Expecting:
644 6
Tim Peters8485b562004-08-04 18:46:34 +0000645 ok
646 (0, 3)
647
648If the `verbose` flag is unspecified, then the output will be verbose
649iff `-v` appears in sys.argv:
650
651 >>> # Save the real sys.argv list.
652 >>> old_argv = sys.argv
653
654 >>> # If -v does not appear in sys.argv, then output isn't verbose.
655 >>> sys.argv = ['test']
656 >>> doctest.DocTestRunner().run(test)
657 (0, 3)
658
659 >>> # If -v does appear in sys.argv, then output is verbose.
660 >>> sys.argv = ['test', '-v']
661 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000662 Trying:
663 x = 12
664 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000665 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000666 Trying:
667 print x
668 Expecting:
669 12
Tim Peters8485b562004-08-04 18:46:34 +0000670 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000671 Trying:
672 x/2
673 Expecting:
674 6
Tim Peters8485b562004-08-04 18:46:34 +0000675 ok
676 (0, 3)
677
678 >>> # Restore sys.argv
679 >>> sys.argv = old_argv
680
681In the remaining examples, the test runner's verbosity will be
682explicitly set, to ensure that the test behavior is consistent.
683 """
684 def exceptions(): r"""
685Tests of `DocTestRunner`'s exception handling.
686
687An expected exception is specified with a traceback message. The
688lines between the first line and the type/value may be omitted or
689replaced with any other string:
690
691 >>> def f(x):
692 ... '''
693 ... >>> x = 12
694 ... >>> print x/0
695 ... Traceback (most recent call last):
696 ... ZeroDivisionError: integer division or modulo by zero
697 ... '''
698 >>> test = doctest.DocTestFinder().find(f)[0]
699 >>> doctest.DocTestRunner(verbose=False).run(test)
700 (0, 2)
701
Edward Loper19b19582004-08-25 23:07:03 +0000702An example may not generate output before it raises an exception; if
703it does, then the traceback message will not be recognized as
704signaling an expected exception, so the example will be reported as an
705unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000706
707 >>> def f(x):
708 ... '''
709 ... >>> x = 12
710 ... >>> print 'pre-exception output', x/0
711 ... pre-exception output
712 ... Traceback (most recent call last):
713 ... ZeroDivisionError: integer division or modulo by zero
714 ... '''
715 >>> test = doctest.DocTestFinder().find(f)[0]
716 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000717 ... # doctest: +ELLIPSIS
718 **********************************************************************
719 Line 3, in f
720 Failed example:
721 print 'pre-exception output', x/0
722 Exception raised:
723 ...
724 ZeroDivisionError: integer division or modulo by zero
725 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000726
727Exception messages may contain newlines:
728
729 >>> def f(x):
730 ... r'''
731 ... >>> raise ValueError, 'multi\nline\nmessage'
732 ... Traceback (most recent call last):
733 ... ValueError: multi
734 ... line
735 ... message
736 ... '''
737 >>> test = doctest.DocTestFinder().find(f)[0]
738 >>> doctest.DocTestRunner(verbose=False).run(test)
739 (0, 1)
740
741If an exception is expected, but an exception with the wrong type or
742message is raised, then it is reported as a failure:
743
744 >>> def f(x):
745 ... r'''
746 ... >>> raise ValueError, 'message'
747 ... Traceback (most recent call last):
748 ... ValueError: wrong message
749 ... '''
750 >>> test = doctest.DocTestFinder().find(f)[0]
751 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000752 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000753 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000754 Line 2, in f
755 Failed example:
756 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000757 Expected:
758 Traceback (most recent call last):
759 ValueError: wrong message
760 Got:
761 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000762 ...
Tim Peters8485b562004-08-04 18:46:34 +0000763 ValueError: message
764 (1, 1)
765
766If an exception is raised but not expected, then it is reported as an
767unexpected exception:
768
Tim Peters8485b562004-08-04 18:46:34 +0000769 >>> def f(x):
770 ... r'''
771 ... >>> 1/0
772 ... 0
773 ... '''
774 >>> test = doctest.DocTestFinder().find(f)[0]
775 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000776 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000777 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000778 Line 2, in f
779 Failed example:
780 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000781 Exception raised:
782 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000783 ...
Tim Peters8485b562004-08-04 18:46:34 +0000784 ZeroDivisionError: integer division or modulo by zero
785 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000786"""
787 def optionflags(): r"""
788Tests of `DocTestRunner`'s option flag handling.
789
790Several option flags can be used to customize the behavior of the test
791runner. These are defined as module constants in doctest, and passed
792to the DocTestRunner constructor (multiple constants should be or-ed
793together).
794
795The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
796and 1/0:
797
798 >>> def f(x):
799 ... '>>> True\n1\n'
800
801 >>> # Without the flag:
802 >>> test = doctest.DocTestFinder().find(f)[0]
803 >>> doctest.DocTestRunner(verbose=False).run(test)
804 (0, 1)
805
806 >>> # With the flag:
807 >>> test = doctest.DocTestFinder().find(f)[0]
808 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
809 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
810 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000811 Line 1, in f
812 Failed example:
813 True
814 Expected:
815 1
816 Got:
817 True
Tim Peters8485b562004-08-04 18:46:34 +0000818 (1, 1)
819
820The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
821and the '<BLANKLINE>' marker:
822
823 >>> def f(x):
824 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
825
826 >>> # Without the flag:
827 >>> test = doctest.DocTestFinder().find(f)[0]
828 >>> doctest.DocTestRunner(verbose=False).run(test)
829 (0, 1)
830
831 >>> # With the flag:
832 >>> test = doctest.DocTestFinder().find(f)[0]
833 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
834 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
835 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000836 Line 1, in f
837 Failed example:
838 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000839 Expected:
840 a
841 <BLANKLINE>
842 b
843 Got:
844 a
845 <BLANKLINE>
846 b
847 (1, 1)
848
849The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
850treated as equal:
851
852 >>> def f(x):
853 ... '>>> print 1, 2, 3\n 1 2\n 3'
854
855 >>> # Without the flag:
856 >>> test = doctest.DocTestFinder().find(f)[0]
857 >>> doctest.DocTestRunner(verbose=False).run(test)
858 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000859 Line 1, in f
860 Failed example:
861 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000862 Expected:
863 1 2
864 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000865 Got:
866 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000867 (1, 1)
868
869 >>> # With the flag:
870 >>> test = doctest.DocTestFinder().find(f)[0]
871 >>> flags = doctest.NORMALIZE_WHITESPACE
872 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
873 (0, 1)
874
Tim Peters026f8dc2004-08-19 16:38:58 +0000875 An example from the docs:
876 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
877 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
878 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
879
Tim Peters8485b562004-08-04 18:46:34 +0000880The ELLIPSIS flag causes ellipsis marker ("...") in the expected
881output to match any substring in the actual output:
882
883 >>> def f(x):
884 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
885
886 >>> # Without the flag:
887 >>> test = doctest.DocTestFinder().find(f)[0]
888 >>> doctest.DocTestRunner(verbose=False).run(test)
889 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000890 Line 1, in f
891 Failed example:
892 print range(15)
893 Expected:
894 [0, 1, 2, ..., 14]
895 Got:
896 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +0000897 (1, 1)
898
899 >>> # With the flag:
900 >>> test = doctest.DocTestFinder().find(f)[0]
901 >>> flags = doctest.ELLIPSIS
902 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
903 (0, 1)
904
Tim Peterse594bee2004-08-22 01:47:51 +0000905 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +0000906
907 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +0000908 ... print i**2, #doctest: +ELLIPSIS
909 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +0000910
Tim Peters026f8dc2004-08-19 16:38:58 +0000911 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000912
913 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +0000914 ... print i,
915 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +0000916
Tim Peters026f8dc2004-08-19 16:38:58 +0000917 Examples from the docs:
918
919 >>> print range(20) # doctest:+ELLIPSIS
920 [0, 1, ..., 18, 19]
921
922 >>> print range(20) # doctest: +ELLIPSIS
923 ... # doctest: +NORMALIZE_WHITESPACE
924 [0, 1, ..., 18, 19]
925
Edward Loper71f55af2004-08-26 01:41:51 +0000926The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +0000927and actual outputs to be displayed using a unified diff:
928
929 >>> def f(x):
930 ... r'''
931 ... >>> print '\n'.join('abcdefg')
932 ... a
933 ... B
934 ... c
935 ... d
936 ... f
937 ... g
938 ... h
939 ... '''
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 2, in f
946 Failed example:
947 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +0000948 Expected:
949 a
950 B
951 c
952 d
953 f
954 g
955 h
956 Got:
957 a
958 b
959 c
960 d
961 e
962 f
963 g
964 (1, 1)
965
966 >>> # With the flag:
967 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +0000968 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +0000969 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
970 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000971 Line 2, in f
972 Failed example:
973 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +0000974 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +0000975 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +0000976 a
977 -B
978 +b
979 c
980 d
981 +e
982 f
983 g
984 -h
Tim Peters8485b562004-08-04 18:46:34 +0000985 (1, 1)
986
Edward Loper71f55af2004-08-26 01:41:51 +0000987The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +0000988and actual outputs to be displayed using a context diff:
989
Edward Loper71f55af2004-08-26 01:41:51 +0000990 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +0000991 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +0000992 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +0000993 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
994 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000995 Line 2, in f
996 Failed example:
997 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +0000998 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +0000999 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001000 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001001 a
1002 ! B
1003 c
1004 d
1005 f
1006 g
1007 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001008 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001009 a
1010 ! b
1011 c
1012 d
1013 + e
1014 f
1015 g
Tim Peters8485b562004-08-04 18:46:34 +00001016 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001017
1018
Edward Loper71f55af2004-08-26 01:41:51 +00001019The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001020used by the popular ndiff.py utility. This does intraline difference
1021marking, as well as interline differences.
1022
1023 >>> def f(x):
1024 ... r'''
1025 ... >>> print "a b c d e f g h i j k l m"
1026 ... a b c d e f g h i j k 1 m
1027 ... '''
1028 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001029 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001030 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1031 **********************************************************************
1032 Line 2, in f
1033 Failed example:
1034 print "a b c d e f g h i j k l m"
1035 Differences (ndiff with -expected +actual):
1036 - a b c d e f g h i j k 1 m
1037 ? ^
1038 + a b c d e f g h i j k l m
1039 ? + ++ ^
Tim Petersc6cbab02004-08-22 19:43:28 +00001040 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001041
1042The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1043failing example:
1044
1045 >>> def f(x):
1046 ... r'''
1047 ... >>> print 1 # first success
1048 ... 1
1049 ... >>> print 2 # first failure
1050 ... 200
1051 ... >>> print 3 # second failure
1052 ... 300
1053 ... >>> print 4 # second success
1054 ... 4
1055 ... >>> print 5 # third failure
1056 ... 500
1057 ... '''
1058 >>> test = doctest.DocTestFinder().find(f)[0]
1059 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1060 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1061 **********************************************************************
1062 Line 4, in f
1063 Failed example:
1064 print 2 # first failure
1065 Expected:
1066 200
1067 Got:
1068 2
1069 (3, 5)
1070
1071However, output from `report_start` is not supressed:
1072
1073 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
1074 Trying:
1075 print 1 # first success
1076 Expecting:
1077 1
1078 ok
1079 Trying:
1080 print 2 # first failure
1081 Expecting:
1082 200
1083 **********************************************************************
1084 Line 4, in f
1085 Failed example:
1086 print 2 # first failure
1087 Expected:
1088 200
1089 Got:
1090 2
1091 (3, 5)
1092
1093For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1094count as failures:
1095
1096 >>> def f(x):
1097 ... r'''
1098 ... >>> print 1 # first success
1099 ... 1
1100 ... >>> raise ValueError(2) # first failure
1101 ... 200
1102 ... >>> print 3 # second failure
1103 ... 300
1104 ... >>> print 4 # second success
1105 ... 4
1106 ... >>> print 5 # third failure
1107 ... 500
1108 ... '''
1109 >>> test = doctest.DocTestFinder().find(f)[0]
1110 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1111 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1112 ... # doctest: +ELLIPSIS
1113 **********************************************************************
1114 Line 4, in f
1115 Failed example:
1116 raise ValueError(2) # first failure
1117 Exception raised:
1118 ...
1119 ValueError: 2
1120 (3, 5)
1121
Tim Petersc6cbab02004-08-22 19:43:28 +00001122 """
1123
Tim Peters8485b562004-08-04 18:46:34 +00001124 def option_directives(): r"""
1125Tests of `DocTestRunner`'s option directive mechanism.
1126
Edward Loper74bca7a2004-08-12 02:27:44 +00001127Option directives can be used to turn option flags on or off for a
1128single example. To turn an option on for an example, follow that
1129example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001130
1131 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001132 ... >>> print range(10) # should fail: no ellipsis
1133 ... [0, 1, ..., 9]
1134 ...
1135 ... >>> print range(10) # doctest: +ELLIPSIS
1136 ... [0, 1, ..., 9]
1137 ... '''
1138 >>> test = doctest.DocTestFinder().find(f)[0]
1139 >>> doctest.DocTestRunner(verbose=False).run(test)
1140 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001141 Line 2, in f
1142 Failed example:
1143 print range(10) # should fail: no ellipsis
1144 Expected:
1145 [0, 1, ..., 9]
1146 Got:
1147 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001148 (1, 2)
1149
1150To turn an option off for an example, follow that example with a
1151comment of the form ``# doctest: -OPTION``:
1152
1153 >>> def f(x): r'''
1154 ... >>> print range(10)
1155 ... [0, 1, ..., 9]
1156 ...
1157 ... >>> # should fail: no ellipsis
1158 ... >>> print range(10) # doctest: -ELLIPSIS
1159 ... [0, 1, ..., 9]
1160 ... '''
1161 >>> test = doctest.DocTestFinder().find(f)[0]
1162 >>> doctest.DocTestRunner(verbose=False,
1163 ... optionflags=doctest.ELLIPSIS).run(test)
1164 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001165 Line 6, in f
1166 Failed example:
1167 print range(10) # doctest: -ELLIPSIS
1168 Expected:
1169 [0, 1, ..., 9]
1170 Got:
1171 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001172 (1, 2)
1173
1174Option directives affect only the example that they appear with; they
1175do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001176
Edward Loper74bca7a2004-08-12 02:27:44 +00001177 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001178 ... >>> print range(10) # Should fail: no ellipsis
1179 ... [0, 1, ..., 9]
1180 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001181 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001182 ... [0, 1, ..., 9]
1183 ...
Tim Peters8485b562004-08-04 18:46:34 +00001184 ... >>> print range(10) # Should fail: no ellipsis
1185 ... [0, 1, ..., 9]
1186 ... '''
1187 >>> test = doctest.DocTestFinder().find(f)[0]
1188 >>> doctest.DocTestRunner(verbose=False).run(test)
1189 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001190 Line 2, in f
1191 Failed example:
1192 print range(10) # Should fail: no ellipsis
1193 Expected:
1194 [0, 1, ..., 9]
1195 Got:
1196 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001197 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001198 Line 8, in f
1199 Failed example:
1200 print range(10) # Should fail: no ellipsis
1201 Expected:
1202 [0, 1, ..., 9]
1203 Got:
1204 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001205 (2, 3)
1206
Edward Loper74bca7a2004-08-12 02:27:44 +00001207Multiple options may be modified by a single option directive. They
1208may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001209
1210 >>> def f(x): r'''
1211 ... >>> print range(10) # Should fail
1212 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001213 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001214 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001215 ... [0, 1, ..., 9]
1216 ... '''
1217 >>> test = doctest.DocTestFinder().find(f)[0]
1218 >>> doctest.DocTestRunner(verbose=False).run(test)
1219 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001220 Line 2, in f
1221 Failed example:
1222 print range(10) # Should fail
1223 Expected:
1224 [0, 1, ..., 9]
1225 Got:
1226 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001227 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001228
1229 >>> def f(x): r'''
1230 ... >>> print range(10) # Should fail
1231 ... [0, 1, ..., 9]
1232 ... >>> print range(10) # Should succeed
1233 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1234 ... [0, 1, ..., 9]
1235 ... '''
1236 >>> test = doctest.DocTestFinder().find(f)[0]
1237 >>> doctest.DocTestRunner(verbose=False).run(test)
1238 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001239 Line 2, in f
1240 Failed example:
1241 print range(10) # Should fail
1242 Expected:
1243 [0, 1, ..., 9]
1244 Got:
1245 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001246 (1, 2)
1247
1248 >>> def f(x): r'''
1249 ... >>> print range(10) # Should fail
1250 ... [0, 1, ..., 9]
1251 ... >>> print range(10) # Should succeed
1252 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1253 ... [0, 1, ..., 9]
1254 ... '''
1255 >>> test = doctest.DocTestFinder().find(f)[0]
1256 >>> doctest.DocTestRunner(verbose=False).run(test)
1257 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001258 Line 2, in f
1259 Failed example:
1260 print range(10) # Should fail
1261 Expected:
1262 [0, 1, ..., 9]
1263 Got:
1264 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001265 (1, 2)
1266
1267The option directive may be put on the line following the source, as
1268long as a continuation prompt is used:
1269
1270 >>> def f(x): r'''
1271 ... >>> print range(10)
1272 ... ... # doctest: +ELLIPSIS
1273 ... [0, 1, ..., 9]
1274 ... '''
1275 >>> test = doctest.DocTestFinder().find(f)[0]
1276 >>> doctest.DocTestRunner(verbose=False).run(test)
1277 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001278
Edward Loper74bca7a2004-08-12 02:27:44 +00001279For examples with multi-line source, the option directive may appear
1280at the end of any line:
1281
1282 >>> def f(x): r'''
1283 ... >>> for x in range(10): # doctest: +ELLIPSIS
1284 ... ... print x,
1285 ... 0 1 2 ... 9
1286 ...
1287 ... >>> for x in range(10):
1288 ... ... print x, # doctest: +ELLIPSIS
1289 ... 0 1 2 ... 9
1290 ... '''
1291 >>> test = doctest.DocTestFinder().find(f)[0]
1292 >>> doctest.DocTestRunner(verbose=False).run(test)
1293 (0, 2)
1294
1295If more than one line of an example with multi-line source has an
1296option directive, then they are combined:
1297
1298 >>> def f(x): r'''
1299 ... Should fail (option directive not on the last line):
1300 ... >>> for x in range(10): # doctest: +ELLIPSIS
1301 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1302 ... 0 1 2...9
1303 ... '''
1304 >>> test = doctest.DocTestFinder().find(f)[0]
1305 >>> doctest.DocTestRunner(verbose=False).run(test)
1306 (0, 1)
1307
1308It is an error to have a comment of the form ``# doctest:`` that is
1309*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1310``OPTION`` is an option that has been registered with
1311`register_option`:
1312
1313 >>> # Error: Option not registered
1314 >>> s = '>>> print 12 #doctest: +BADOPTION'
1315 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1316 Traceback (most recent call last):
1317 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1318
1319 >>> # Error: No + or - prefix
1320 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1321 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1322 Traceback (most recent call last):
1323 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1324
1325It is an error to use an option directive on a line that contains no
1326source:
1327
1328 >>> s = '>>> # doctest: +ELLIPSIS'
1329 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1330 Traceback (most recent call last):
1331 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 +00001332"""
1333
1334def test_testsource(): r"""
1335Unit tests for `testsource()`.
1336
1337The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001338test with that name in that module, and converts it to a script. The
1339example code is converted to regular Python code. The surrounding
1340words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001341
1342 >>> import test.test_doctest
1343 >>> name = 'test.test_doctest.sample_func'
1344 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001345 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001346 #
Tim Peters8485b562004-08-04 18:46:34 +00001347 print sample_func(22)
1348 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001349 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001350 #
Edward Lopera5db6002004-08-12 02:41:30 +00001351 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001352
1353 >>> name = 'test.test_doctest.SampleNewStyleClass'
1354 >>> print doctest.testsource(test.test_doctest, name)
1355 print '1\n2\n3'
1356 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001357 ## 1
1358 ## 2
1359 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001360
1361 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1362 >>> print doctest.testsource(test.test_doctest, name)
1363 print SampleClass.a_classmethod(10)
1364 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001365 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001366 print SampleClass(0).a_classmethod(10)
1367 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001368 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001369"""
1370
1371def test_debug(): r"""
1372
1373Create a docstring that we want to debug:
1374
1375 >>> s = '''
1376 ... >>> x = 12
1377 ... >>> print x
1378 ... 12
1379 ... '''
1380
1381Create some fake stdin input, to feed to the debugger:
1382
1383 >>> import tempfile
1384 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1385 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1386 >>> fake_stdin.seek(0)
1387 >>> real_stdin = sys.stdin
1388 >>> sys.stdin = fake_stdin
1389
1390Run the debugger on the docstring, and then restore sys.stdin.
1391
Tim Peters8485b562004-08-04 18:46:34 +00001392 >>> try:
1393 ... doctest.debug_src(s)
1394 ... finally:
1395 ... sys.stdin = real_stdin
1396 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001397 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001398 > <string>(1)?()
1399 (Pdb) 12
1400 --Return--
1401 > <string>(1)?()->None
1402 (Pdb) 12
1403 (Pdb)
1404
1405"""
1406
Jim Fulton356fd192004-08-09 11:34:47 +00001407def test_pdb_set_trace():
1408 r"""Using pdb.set_trace from a doctest
1409
Tim Peters413ced62004-08-09 15:43:47 +00001410 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001411 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001412 you use it. The doctest module changes sys.stdout so that it can
1413 capture program output. It also temporarily replaces pdb.set_trace
1414 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001415 see debugger output.
1416
1417 >>> doc = '''
1418 ... >>> x = 42
1419 ... >>> import pdb; pdb.set_trace()
1420 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001421 >>> parser = doctest.DocTestParser()
1422 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001423 >>> runner = doctest.DocTestRunner(verbose=False)
1424
1425 To demonstrate this, we'll create a fake standard input that
1426 captures our debugger input:
1427
1428 >>> import tempfile
1429 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1430 >>> fake_stdin.write('\n'.join([
1431 ... 'up', # up out of pdb.set_trace
1432 ... 'up', # up again to get out of our wrapper
1433 ... 'print x', # print data defined by the example
1434 ... 'continue', # stop debugging
1435 ... '']))
1436 >>> fake_stdin.seek(0)
1437 >>> real_stdin = sys.stdin
1438 >>> sys.stdin = fake_stdin
1439
Edward Loper74bca7a2004-08-12 02:27:44 +00001440 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001441 --Return--
1442 > ...set_trace()->None
1443 -> Pdb().set_trace()
1444 (Pdb) > ...set_trace()
1445 -> real_pdb_set_trace()
1446 (Pdb) > <string>(1)?()
1447 (Pdb) 42
1448 (Pdb) (0, 2)
1449
1450 >>> sys.stdin = real_stdin
1451 >>> fake_stdin.close()
1452
1453 You can also put pdb.set_trace in a function called from a test:
1454
1455 >>> def calls_set_trace():
1456 ... y=2
1457 ... import pdb; pdb.set_trace()
1458
1459 >>> doc = '''
1460 ... >>> x=1
1461 ... >>> calls_set_trace()
1462 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001463 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001464 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1465 >>> fake_stdin.write('\n'.join([
1466 ... 'up', # up out of pdb.set_trace
1467 ... 'up', # up again to get out of our wrapper
1468 ... 'print y', # print data defined in the function
1469 ... 'up', # out of function
1470 ... 'print x', # print data defined by the example
1471 ... 'continue', # stop debugging
1472 ... '']))
1473 >>> fake_stdin.seek(0)
1474 >>> real_stdin = sys.stdin
1475 >>> sys.stdin = fake_stdin
1476
Edward Loper74bca7a2004-08-12 02:27:44 +00001477 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001478 --Return--
1479 > ...set_trace()->None
1480 -> Pdb().set_trace()
1481 (Pdb) ...set_trace()
1482 -> real_pdb_set_trace()
1483 (Pdb) > <string>(3)calls_set_trace()
1484 (Pdb) 2
1485 (Pdb) > <string>(1)?()
1486 (Pdb) 1
1487 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001488 """
1489
Tim Peters19397e52004-08-06 22:02:59 +00001490def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001491 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001492
1493 We create a Suite by providing a module. A module can be provided
1494 by passing a module object:
1495
1496 >>> import unittest
1497 >>> import test.sample_doctest
1498 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1499 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001500 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001501
1502 We can also supply the module by name:
1503
1504 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1505 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001506 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001507
1508 We can use the current module:
1509
1510 >>> suite = test.sample_doctest.test_suite()
1511 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001512 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001513
1514 We can supply global variables. If we pass globs, they will be
1515 used instead of the module globals. Here we'll pass an empty
1516 globals, triggering an extra error:
1517
1518 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1519 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001520 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001521
1522 Alternatively, we can provide extra globals. Here we'll make an
1523 error go away by providing an extra global variable:
1524
1525 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1526 ... extraglobs={'y': 1})
1527 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001528 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001529
1530 You can pass option flags. Here we'll cause an extra error
1531 by disabling the blank-line feature:
1532
1533 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001534 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001535 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001536 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001537
Tim Peters1e277ee2004-08-07 05:37:52 +00001538 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001539
1540 >>> def setUp():
1541 ... import test.test_doctest
1542 ... test.test_doctest.sillySetup = True
1543
1544 >>> def tearDown():
1545 ... import test.test_doctest
1546 ... del test.test_doctest.sillySetup
1547
1548 Here, we installed a silly variable that the test expects:
1549
1550 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1551 ... setUp=setUp, tearDown=tearDown)
1552 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001553 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001554
1555 But the tearDown restores sanity:
1556
1557 >>> import test.test_doctest
1558 >>> test.test_doctest.sillySetup
1559 Traceback (most recent call last):
1560 ...
1561 AttributeError: 'module' object has no attribute 'sillySetup'
1562
1563 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001564 use a custom test_finder to to run just the test named bar.
1565 However, the test in the module docstring, and the two tests
1566 in the module __test__ dict, aren't filtered, so we actually
1567 run three tests besides bar's. The filtering mechanisms are
1568 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001569
1570 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001571 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001572 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1573 ... test_finder=finder)
1574 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001575 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001576 """
1577
1578def test_DocFileSuite():
1579 """We can test tests found in text files using a DocFileSuite.
1580
1581 We create a suite by providing the names of one or more text
1582 files that include examples:
1583
1584 >>> import unittest
1585 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1586 ... 'test_doctest2.txt')
1587 >>> suite.run(unittest.TestResult())
1588 <unittest.TestResult run=2 errors=0 failures=2>
1589
1590 The test files are looked for in the directory containing the
1591 calling module. A package keyword argument can be provided to
1592 specify a different relative location.
1593
1594 >>> import unittest
1595 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1596 ... 'test_doctest2.txt',
1597 ... package='test')
1598 >>> suite.run(unittest.TestResult())
1599 <unittest.TestResult run=2 errors=0 failures=2>
1600
1601 Note that '/' should be used as a path separator. It will be
1602 converted to a native separator at run time:
1603
1604
1605 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1606 >>> suite.run(unittest.TestResult())
1607 <unittest.TestResult run=1 errors=0 failures=1>
1608
1609 You can specify initial global variables:
1610
1611 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1612 ... 'test_doctest2.txt',
1613 ... globs={'favorite_color': 'blue'})
1614 >>> suite.run(unittest.TestResult())
1615 <unittest.TestResult run=2 errors=0 failures=1>
1616
1617 In this case, we supplied a missing favorite color. You can
1618 provide doctest options:
1619
1620 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1621 ... 'test_doctest2.txt',
1622 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1623 ... globs={'favorite_color': 'blue'})
1624 >>> suite.run(unittest.TestResult())
1625 <unittest.TestResult run=2 errors=0 failures=2>
1626
1627 And, you can provide setUp and tearDown functions:
1628
1629 You can supply setUp and teatDoen functions:
1630
1631 >>> def setUp():
1632 ... import test.test_doctest
1633 ... test.test_doctest.sillySetup = True
1634
1635 >>> def tearDown():
1636 ... import test.test_doctest
1637 ... del test.test_doctest.sillySetup
1638
1639 Here, we installed a silly variable that the test expects:
1640
1641 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1642 ... 'test_doctest2.txt',
1643 ... setUp=setUp, tearDown=tearDown)
1644 >>> suite.run(unittest.TestResult())
1645 <unittest.TestResult run=2 errors=0 failures=1>
1646
1647 But the tearDown restores sanity:
1648
1649 >>> import test.test_doctest
1650 >>> test.test_doctest.sillySetup
1651 Traceback (most recent call last):
1652 ...
1653 AttributeError: 'module' object has no attribute 'sillySetup'
1654
1655 """
1656
Jim Fulton07a349c2004-08-22 14:10:00 +00001657def test_trailing_space_in_test():
1658 """
Tim Petersa7def722004-08-23 22:13:22 +00001659 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001660
Jim Fulton07a349c2004-08-22 14:10:00 +00001661 >>> x, y = 'foo', ''
1662 >>> print x, y
1663 foo \n
1664 """
Tim Peters19397e52004-08-06 22:02:59 +00001665
Tim Petersa7def722004-08-23 22:13:22 +00001666# old_test1, ... used to live in doctest.py, but cluttered it. Note
1667# that these use the deprecated doctest.Tester, so should go away (or
1668# be rewritten) someday.
1669
1670# Ignore all warnings about the use of class Tester in this module.
1671# Note that the name of this module may differ depending on how it's
1672# imported, so the use of __name__ is important.
1673warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1674 __name__, 0)
1675
1676def old_test1(): r"""
1677>>> from doctest import Tester
1678>>> t = Tester(globs={'x': 42}, verbose=0)
1679>>> t.runstring(r'''
1680... >>> x = x * 2
1681... >>> print x
1682... 42
1683... ''', 'XYZ')
1684**********************************************************************
1685Line 3, in XYZ
1686Failed example:
1687 print x
1688Expected:
1689 42
1690Got:
1691 84
1692(1, 2)
1693>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1694(0, 2)
1695>>> t.summarize()
1696**********************************************************************
16971 items had failures:
1698 1 of 2 in XYZ
1699***Test Failed*** 1 failures.
1700(1, 4)
1701>>> t.summarize(verbose=1)
17021 items passed all tests:
1703 2 tests in example2
1704**********************************************************************
17051 items had failures:
1706 1 of 2 in XYZ
17074 tests in 2 items.
17083 passed and 1 failed.
1709***Test Failed*** 1 failures.
1710(1, 4)
1711"""
1712
1713def old_test2(): r"""
1714 >>> from doctest import Tester
1715 >>> t = Tester(globs={}, verbose=1)
1716 >>> test = r'''
1717 ... # just an example
1718 ... >>> x = 1 + 2
1719 ... >>> x
1720 ... 3
1721 ... '''
1722 >>> t.runstring(test, "Example")
1723 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00001724 Trying:
1725 x = 1 + 2
1726 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00001727 ok
Edward Loperaacf0832004-08-26 01:19:50 +00001728 Trying:
1729 x
1730 Expecting:
1731 3
Tim Petersa7def722004-08-23 22:13:22 +00001732 ok
1733 0 of 2 examples failed in string Example
1734 (0, 2)
1735"""
1736
1737def old_test3(): r"""
1738 >>> from doctest import Tester
1739 >>> t = Tester(globs={}, verbose=0)
1740 >>> def _f():
1741 ... '''Trivial docstring example.
1742 ... >>> assert 2 == 2
1743 ... '''
1744 ... return 32
1745 ...
1746 >>> t.rundoc(_f) # expect 0 failures in 1 example
1747 (0, 1)
1748"""
1749
1750def old_test4(): """
1751 >>> import new
1752 >>> m1 = new.module('_m1')
1753 >>> m2 = new.module('_m2')
1754 >>> test_data = \"""
1755 ... def _f():
1756 ... '''>>> assert 1 == 1
1757 ... '''
1758 ... def g():
1759 ... '''>>> assert 2 != 1
1760 ... '''
1761 ... class H:
1762 ... '''>>> assert 2 > 1
1763 ... '''
1764 ... def bar(self):
1765 ... '''>>> assert 1 < 2
1766 ... '''
1767 ... \"""
1768 >>> exec test_data in m1.__dict__
1769 >>> exec test_data in m2.__dict__
1770 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
1771
1772 Tests that objects outside m1 are excluded:
1773
1774 >>> from doctest import Tester
1775 >>> t = Tester(globs={}, verbose=0)
1776 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
1777 (0, 4)
1778
1779 Once more, not excluding stuff outside m1:
1780
1781 >>> t = Tester(globs={}, verbose=0)
1782 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
1783 (0, 8)
1784
1785 The exclusion of objects from outside the designated module is
1786 meant to be invoked automagically by testmod.
1787
1788 >>> doctest.testmod(m1, verbose=False)
1789 (0, 4)
1790"""
1791
Tim Peters8485b562004-08-04 18:46:34 +00001792######################################################################
1793## Main
1794######################################################################
1795
1796def test_main():
1797 # Check the doctest cases in doctest itself:
1798 test_support.run_doctest(doctest, verbosity=True)
1799 # Check the doctest cases defined here:
1800 from test import test_doctest
1801 test_support.run_doctest(test_doctest, verbosity=True)
1802
1803import trace, sys, re, StringIO
1804def test_coverage(coverdir):
1805 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1806 trace=0, count=1)
1807 tracer.run('reload(doctest); test_main()')
1808 r = tracer.results()
1809 print 'Writing coverage results...'
1810 r.write_results(show_missing=True, summary=True,
1811 coverdir=coverdir)
1812
1813if __name__ == '__main__':
1814 if '-c' in sys.argv:
1815 test_coverage('/tmp/doctest.cover')
1816 else:
1817 test_main()