blob: 8e651d05a91a647a4883af9c444286479ff97b02 [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
7
8######################################################################
9## Sample Objects (used by test cases)
10######################################################################
11
12def sample_func(v):
13 """
Tim Peters19397e52004-08-06 22:02:59 +000014 Blah blah
15
Tim Peters8485b562004-08-04 18:46:34 +000016 >>> print sample_func(22)
17 44
Tim Peters19397e52004-08-06 22:02:59 +000018
19 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000020 """
21 return v+v
22
23class SampleClass:
24 """
25 >>> print 1
26 1
27 """
28 def __init__(self, val):
29 """
30 >>> print SampleClass(12).get()
31 12
32 """
33 self.val = val
34
35 def double(self):
36 """
37 >>> print SampleClass(12).double().get()
38 24
39 """
40 return SampleClass(self.val + self.val)
41
42 def get(self):
43 """
44 >>> print SampleClass(-5).get()
45 -5
46 """
47 return self.val
48
49 def a_staticmethod(v):
50 """
51 >>> print SampleClass.a_staticmethod(10)
52 11
53 """
54 return v+1
55 a_staticmethod = staticmethod(a_staticmethod)
56
57 def a_classmethod(cls, v):
58 """
59 >>> print SampleClass.a_classmethod(10)
60 12
61 >>> print SampleClass(0).a_classmethod(10)
62 12
63 """
64 return v+2
65 a_classmethod = classmethod(a_classmethod)
66
67 a_property = property(get, doc="""
68 >>> print SampleClass(22).a_property
69 22
70 """)
71
72 class NestedClass:
73 """
74 >>> x = SampleClass.NestedClass(5)
75 >>> y = x.square()
76 >>> print y.get()
77 25
78 """
79 def __init__(self, val=0):
80 """
81 >>> print SampleClass.NestedClass().get()
82 0
83 """
84 self.val = val
85 def square(self):
86 return SampleClass.NestedClass(self.val*self.val)
87 def get(self):
88 return self.val
89
90class SampleNewStyleClass(object):
91 r"""
92 >>> print '1\n2\n3'
93 1
94 2
95 3
96 """
97 def __init__(self, val):
98 """
99 >>> print SampleNewStyleClass(12).get()
100 12
101 """
102 self.val = val
103
104 def double(self):
105 """
106 >>> print SampleNewStyleClass(12).double().get()
107 24
108 """
109 return SampleNewStyleClass(self.val + self.val)
110
111 def get(self):
112 """
113 >>> print SampleNewStyleClass(-5).get()
114 -5
115 """
116 return self.val
117
118######################################################################
119## Test Cases
120######################################################################
121
122def test_Example(): r"""
123Unit tests for the `Example` class.
124
125Example is a simple container class that holds a source code string,
126an expected output string, and a line number (within the docstring):
127
128 >>> example = doctest.Example('print 1', '1\n', 0)
129 >>> (example.source, example.want, example.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000130 ('print 1\n', '1\n', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000131
Tim Petersbb431472004-08-09 03:51:46 +0000132The `source` string ends in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000133
Tim Petersbb431472004-08-09 03:51:46 +0000134 Source spans a single line: no terminating newline.
Tim Peters8485b562004-08-04 18:46:34 +0000135 >>> e = doctest.Example('print 1', '1\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000136 >>> e.source, e.want
137 ('print 1\n', '1\n')
138
Tim Peters8485b562004-08-04 18:46:34 +0000139 >>> e = doctest.Example('print 1\n', '1\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000140 >>> e.source, e.want
141 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000142
Tim Petersbb431472004-08-09 03:51:46 +0000143 Source spans multiple lines: require terminating newline.
Tim Peters8485b562004-08-04 18:46:34 +0000144 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000145 >>> e.source, e.want
146 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000147
Tim Petersbb431472004-08-09 03:51:46 +0000148 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n', 0)
149 >>> e.source, e.want
150 ('print 1;\nprint 2\n', '1\n2\n')
151
152The `want` string ends with a newline, unless it's the empty string:
Tim Peters8485b562004-08-04 18:46:34 +0000153
154 >>> e = doctest.Example('print 1', '1\n', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000155 >>> e.source, e.want
156 ('print 1\n', '1\n')
157
Tim Peters8485b562004-08-04 18:46:34 +0000158 >>> e = doctest.Example('print 1', '1', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000159 >>> e.source, e.want
160 ('print 1\n', '1\n')
161
Tim Peters8485b562004-08-04 18:46:34 +0000162 >>> e = doctest.Example('print', '', 0)
Tim Petersbb431472004-08-09 03:51:46 +0000163 >>> e.source, e.want
164 ('print\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000165"""
166
167def test_DocTest(): r"""
168Unit tests for the `DocTest` class.
169
170DocTest is a collection of examples, extracted from a docstring, along
171with information about where the docstring comes from (a name,
172filename, and line number). The docstring is parsed by the `DocTest`
173constructor:
174
175 >>> docstring = '''
176 ... >>> print 12
177 ... 12
178 ...
179 ... Non-example text.
180 ...
181 ... >>> print 'another\example'
182 ... another
183 ... example
184 ... '''
185 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000186 >>> parser = doctest.DocTestParser()
187 >>> test = parser.get_doctest(docstring, globs, 'some_test',
188 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000189 >>> print test
190 <DocTest some_test from some_file:20 (2 examples)>
191 >>> len(test.examples)
192 2
193 >>> e1, e2 = test.examples
194 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000195 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000196 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000197 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000198
199Source information (name, filename, and line number) is available as
200attributes on the doctest object:
201
202 >>> (test.name, test.filename, test.lineno)
203 ('some_test', 'some_file', 20)
204
205The line number of an example within its containing file is found by
206adding the line number of the example and the line number of its
207containing test:
208
209 >>> test.lineno + e1.lineno
210 21
211 >>> test.lineno + e2.lineno
212 26
213
214If the docstring contains inconsistant leading whitespace in the
215expected output of an example, then `DocTest` will raise a ValueError:
216
217 >>> docstring = r'''
218 ... >>> print 'bad\nindentation'
219 ... bad
220 ... indentation
221 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000222 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000223 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000224 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: ' indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000225
226If the docstring contains inconsistent leading whitespace on
227continuation lines, then `DocTest` will raise a ValueError:
228
229 >>> docstring = r'''
230 ... >>> print ('bad indentation',
231 ... ... 2)
232 ... ('bad', 'indentation')
233 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000234 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000235 Traceback (most recent call last):
236 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: ' ... 2)'
237
238If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
239will raise a ValueError:
240
241 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000242 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000243 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000244 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
245
246If there's no blank space after a PS2 prompt ('...'), then `DocTest`
247will raise a ValueError:
248
249 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000250 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000251 Traceback (most recent call last):
252 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
253
Tim Peters8485b562004-08-04 18:46:34 +0000254"""
255
256# [XX] test that it's getting line numbers right.
257def test_DocTestFinder(): r"""
258Unit tests for the `DocTestFinder` class.
259
260DocTestFinder is used to extract DocTests from an object's docstring
261and the docstrings of its contained objects. It can be used with
262modules, functions, classes, methods, staticmethods, classmethods, and
263properties.
264
265Finding Tests in Functions
266~~~~~~~~~~~~~~~~~~~~~~~~~~
267For a function whose docstring contains examples, DocTestFinder.find()
268will return a single test (for that function's docstring):
269
Tim Peters8485b562004-08-04 18:46:34 +0000270 >>> finder = doctest.DocTestFinder()
271 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000272
Edward Loper74bca7a2004-08-12 02:27:44 +0000273 >>> print tests # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000274 [<DocTest sample_func from ...:12 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000275
Tim Peters8485b562004-08-04 18:46:34 +0000276 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000277 >>> (e.source, e.want, e.lineno)
278 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000279
Tim Peters8485b562004-08-04 18:46:34 +0000280If an object has no docstring, then a test is not created for it:
281
282 >>> def no_docstring(v):
283 ... pass
284 >>> finder.find(no_docstring)
285 []
286
287If the function has a docstring with no examples, then a test with no
288examples is returned. (This lets `DocTestRunner` collect statistics
289about which functions have no tests -- but is that useful? And should
290an empty test also be created when there's no docstring?)
291
292 >>> def no_examples(v):
293 ... ''' no doctest examples '''
294 >>> finder.find(no_examples)
295 [<DocTest no_examples from None:1 (no examples)>]
296
297Finding Tests in Classes
298~~~~~~~~~~~~~~~~~~~~~~~~
299For a class, DocTestFinder will create a test for the class's
300docstring, and will recursively explore its contents, including
301methods, classmethods, staticmethods, properties, and nested classes.
302
303 >>> finder = doctest.DocTestFinder()
304 >>> tests = finder.find(SampleClass)
305 >>> tests.sort()
306 >>> for t in tests:
307 ... print '%2s %s' % (len(t.examples), t.name)
308 1 SampleClass
309 3 SampleClass.NestedClass
310 1 SampleClass.NestedClass.__init__
311 1 SampleClass.__init__
312 2 SampleClass.a_classmethod
313 1 SampleClass.a_property
314 1 SampleClass.a_staticmethod
315 1 SampleClass.double
316 1 SampleClass.get
317
318New-style classes are also supported:
319
320 >>> tests = finder.find(SampleNewStyleClass)
321 >>> tests.sort()
322 >>> for t in tests:
323 ... print '%2s %s' % (len(t.examples), t.name)
324 1 SampleNewStyleClass
325 1 SampleNewStyleClass.__init__
326 1 SampleNewStyleClass.double
327 1 SampleNewStyleClass.get
328
329Finding Tests in Modules
330~~~~~~~~~~~~~~~~~~~~~~~~
331For a module, DocTestFinder will create a test for the class's
332docstring, and will recursively explore its contents, including
333functions, classes, and the `__test__` dictionary, if it exists:
334
335 >>> # A module
336 >>> import new
337 >>> m = new.module('some_module')
338 >>> def triple(val):
339 ... '''
340 ... >>> print tripple(11)
341 ... 33
342 ... '''
343 ... return val*3
344 >>> m.__dict__.update({
345 ... 'sample_func': sample_func,
346 ... 'SampleClass': SampleClass,
347 ... '__doc__': '''
348 ... Module docstring.
349 ... >>> print 'module'
350 ... module
351 ... ''',
352 ... '__test__': {
353 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
354 ... 'c': triple}})
355
356 >>> finder = doctest.DocTestFinder()
357 >>> # Use module=test.test_doctest, to prevent doctest from
358 >>> # ignoring the objects since they weren't defined in m.
359 >>> import test.test_doctest
360 >>> tests = finder.find(m, module=test.test_doctest)
361 >>> tests.sort()
362 >>> for t in tests:
363 ... print '%2s %s' % (len(t.examples), t.name)
364 1 some_module
365 1 some_module.SampleClass
366 3 some_module.SampleClass.NestedClass
367 1 some_module.SampleClass.NestedClass.__init__
368 1 some_module.SampleClass.__init__
369 2 some_module.SampleClass.a_classmethod
370 1 some_module.SampleClass.a_property
371 1 some_module.SampleClass.a_staticmethod
372 1 some_module.SampleClass.double
373 1 some_module.SampleClass.get
374 1 some_module.c
375 2 some_module.d
376 1 some_module.sample_func
377
378Duplicate Removal
379~~~~~~~~~~~~~~~~~
380If a single object is listed twice (under different names), then tests
381will only be generated for it once:
382
Tim Petersf3f57472004-08-08 06:11:48 +0000383 >>> from test import doctest_aliases
384 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000385 >>> tests.sort()
386 >>> print len(tests)
387 2
388 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000389 test.doctest_aliases.TwoNames
390
391 TwoNames.f and TwoNames.g are bound to the same object.
392 We can't guess which will be found in doctest's traversal of
393 TwoNames.__dict__ first, so we have to allow for either.
394
395 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000396 True
397
398Filter Functions
399~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000400A filter function can be used to restrict which objects get examined,
401but this is temporary, undocumented internal support for testmod's
402deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000403
404 >>> def namefilter(prefix, base):
405 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000406 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000407 >>> tests.sort()
408 >>> for t in tests:
409 ... print '%2s %s' % (len(t.examples), t.name)
410 1 SampleClass
411 3 SampleClass.NestedClass
412 1 SampleClass.NestedClass.__init__
413 1 SampleClass.__init__
414 1 SampleClass.double
415 1 SampleClass.get
416
Tim Peters8485b562004-08-04 18:46:34 +0000417If a given object is filtered out, then none of the objects that it
418contains will be added either:
419
420 >>> def namefilter(prefix, base):
421 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000422 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000423 >>> tests.sort()
424 >>> for t in tests:
425 ... print '%2s %s' % (len(t.examples), t.name)
426 1 SampleClass
427 1 SampleClass.__init__
428 2 SampleClass.a_classmethod
429 1 SampleClass.a_property
430 1 SampleClass.a_staticmethod
431 1 SampleClass.double
432 1 SampleClass.get
433
Tim Petersf727c6c2004-08-08 01:48:59 +0000434The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000435object explicitly passed to DocTestFinder:
436
437 >>> def namefilter(prefix, base):
438 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000439 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000440 >>> len(tests)
441 9
442
443Turning off Recursion
444~~~~~~~~~~~~~~~~~~~~~
445DocTestFinder can be told not to look for tests in contained objects
446using the `recurse` flag:
447
448 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
449 >>> tests.sort()
450 >>> for t in tests:
451 ... print '%2s %s' % (len(t.examples), t.name)
452 1 SampleClass
453"""
454
455class test_DocTestRunner:
456 def basics(): r"""
457Unit tests for the `DocTestRunner` class.
458
459DocTestRunner is used to run DocTest test cases, and to accumulate
460statistics. Here's a simple DocTest case we can use:
461
462 >>> def f(x):
463 ... '''
464 ... >>> x = 12
465 ... >>> print x
466 ... 12
467 ... >>> x/2
468 ... 6
469 ... '''
470 >>> test = doctest.DocTestFinder().find(f)[0]
471
472The main DocTestRunner interface is the `run` method, which runs a
473given DocTest case in a given namespace (globs). It returns a tuple
474`(f,t)`, where `f` is the number of failed tests and `t` is the number
475of tried tests.
476
477 >>> doctest.DocTestRunner(verbose=False).run(test)
478 (0, 3)
479
480If any example produces incorrect output, then the test runner reports
481the failure and proceeds to the next example:
482
483 >>> def f(x):
484 ... '''
485 ... >>> x = 12
486 ... >>> print x
487 ... 14
488 ... >>> x/2
489 ... 6
490 ... '''
491 >>> test = doctest.DocTestFinder().find(f)[0]
492 >>> doctest.DocTestRunner(verbose=True).run(test)
493 Trying: x = 12
494 Expecting: nothing
495 ok
496 Trying: print x
497 Expecting: 14
498 **********************************************************************
499 Failure in example: print x
500 from line #2 of f
501 Expected: 14
502 Got: 12
503 Trying: x/2
504 Expecting: 6
505 ok
506 (1, 3)
507"""
508 def verbose_flag(): r"""
509The `verbose` flag makes the test runner generate more detailed
510output:
511
512 >>> def f(x):
513 ... '''
514 ... >>> x = 12
515 ... >>> print x
516 ... 12
517 ... >>> x/2
518 ... 6
519 ... '''
520 >>> test = doctest.DocTestFinder().find(f)[0]
521
522 >>> doctest.DocTestRunner(verbose=True).run(test)
523 Trying: x = 12
524 Expecting: nothing
525 ok
526 Trying: print x
527 Expecting: 12
528 ok
529 Trying: x/2
530 Expecting: 6
531 ok
532 (0, 3)
533
534If the `verbose` flag is unspecified, then the output will be verbose
535iff `-v` appears in sys.argv:
536
537 >>> # Save the real sys.argv list.
538 >>> old_argv = sys.argv
539
540 >>> # If -v does not appear in sys.argv, then output isn't verbose.
541 >>> sys.argv = ['test']
542 >>> doctest.DocTestRunner().run(test)
543 (0, 3)
544
545 >>> # If -v does appear in sys.argv, then output is verbose.
546 >>> sys.argv = ['test', '-v']
547 >>> doctest.DocTestRunner().run(test)
548 Trying: x = 12
549 Expecting: nothing
550 ok
551 Trying: print x
552 Expecting: 12
553 ok
554 Trying: x/2
555 Expecting: 6
556 ok
557 (0, 3)
558
559 >>> # Restore sys.argv
560 >>> sys.argv = old_argv
561
562In the remaining examples, the test runner's verbosity will be
563explicitly set, to ensure that the test behavior is consistent.
564 """
565 def exceptions(): r"""
566Tests of `DocTestRunner`'s exception handling.
567
568An expected exception is specified with a traceback message. The
569lines between the first line and the type/value may be omitted or
570replaced with any other string:
571
572 >>> def f(x):
573 ... '''
574 ... >>> x = 12
575 ... >>> print x/0
576 ... Traceback (most recent call last):
577 ... ZeroDivisionError: integer division or modulo by zero
578 ... '''
579 >>> test = doctest.DocTestFinder().find(f)[0]
580 >>> doctest.DocTestRunner(verbose=False).run(test)
581 (0, 2)
582
583An example may generate output before it raises an exception; if it
584does, then the output must match the expected output:
585
586 >>> def f(x):
587 ... '''
588 ... >>> x = 12
589 ... >>> print 'pre-exception output', x/0
590 ... pre-exception output
591 ... Traceback (most recent call last):
592 ... ZeroDivisionError: integer division or modulo by zero
593 ... '''
594 >>> test = doctest.DocTestFinder().find(f)[0]
595 >>> doctest.DocTestRunner(verbose=False).run(test)
596 (0, 2)
597
598Exception messages may contain newlines:
599
600 >>> def f(x):
601 ... r'''
602 ... >>> raise ValueError, 'multi\nline\nmessage'
603 ... Traceback (most recent call last):
604 ... ValueError: multi
605 ... line
606 ... message
607 ... '''
608 >>> test = doctest.DocTestFinder().find(f)[0]
609 >>> doctest.DocTestRunner(verbose=False).run(test)
610 (0, 1)
611
612If an exception is expected, but an exception with the wrong type or
613message is raised, then it is reported as a failure:
614
615 >>> def f(x):
616 ... r'''
617 ... >>> raise ValueError, 'message'
618 ... Traceback (most recent call last):
619 ... ValueError: wrong message
620 ... '''
621 >>> test = doctest.DocTestFinder().find(f)[0]
622 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000623 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000624 **********************************************************************
625 Failure in example: raise ValueError, 'message'
626 from line #1 of f
627 Expected:
628 Traceback (most recent call last):
629 ValueError: wrong message
630 Got:
631 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000632 ...
Tim Peters8485b562004-08-04 18:46:34 +0000633 ValueError: message
634 (1, 1)
635
636If an exception is raised but not expected, then it is reported as an
637unexpected exception:
638
Tim Peters8485b562004-08-04 18:46:34 +0000639 >>> def f(x):
640 ... r'''
641 ... >>> 1/0
642 ... 0
643 ... '''
644 >>> test = doctest.DocTestFinder().find(f)[0]
645 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000646 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000647 **********************************************************************
648 Failure in example: 1/0
649 from line #1 of f
650 Exception raised:
651 Traceback (most recent call last):
652 ...
653 ZeroDivisionError: integer division or modulo by zero
654 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000655"""
656 def optionflags(): r"""
657Tests of `DocTestRunner`'s option flag handling.
658
659Several option flags can be used to customize the behavior of the test
660runner. These are defined as module constants in doctest, and passed
661to the DocTestRunner constructor (multiple constants should be or-ed
662together).
663
664The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
665and 1/0:
666
667 >>> def f(x):
668 ... '>>> True\n1\n'
669
670 >>> # Without the flag:
671 >>> test = doctest.DocTestFinder().find(f)[0]
672 >>> doctest.DocTestRunner(verbose=False).run(test)
673 (0, 1)
674
675 >>> # With the flag:
676 >>> test = doctest.DocTestFinder().find(f)[0]
677 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
678 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
679 **********************************************************************
680 Failure in example: True
681 from line #0 of f
682 Expected: 1
683 Got: True
684 (1, 1)
685
686The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
687and the '<BLANKLINE>' marker:
688
689 >>> def f(x):
690 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
691
692 >>> # Without the flag:
693 >>> test = doctest.DocTestFinder().find(f)[0]
694 >>> doctest.DocTestRunner(verbose=False).run(test)
695 (0, 1)
696
697 >>> # With the flag:
698 >>> test = doctest.DocTestFinder().find(f)[0]
699 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
700 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
701 **********************************************************************
702 Failure in example: print "a\n\nb"
703 from line #0 of f
704 Expected:
705 a
706 <BLANKLINE>
707 b
708 Got:
709 a
710 <BLANKLINE>
711 b
712 (1, 1)
713
714The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
715treated as equal:
716
717 >>> def f(x):
718 ... '>>> print 1, 2, 3\n 1 2\n 3'
719
720 >>> # Without the flag:
721 >>> test = doctest.DocTestFinder().find(f)[0]
722 >>> doctest.DocTestRunner(verbose=False).run(test)
723 **********************************************************************
724 Failure in example: print 1, 2, 3
725 from line #0 of f
726 Expected:
727 1 2
728 3
729 Got: 1 2 3
730 (1, 1)
731
732 >>> # With the flag:
733 >>> test = doctest.DocTestFinder().find(f)[0]
734 >>> flags = doctest.NORMALIZE_WHITESPACE
735 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
736 (0, 1)
737
738The ELLIPSIS flag causes ellipsis marker ("...") in the expected
739output to match any substring in the actual output:
740
741 >>> def f(x):
742 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
743
744 >>> # Without the flag:
745 >>> test = doctest.DocTestFinder().find(f)[0]
746 >>> doctest.DocTestRunner(verbose=False).run(test)
747 **********************************************************************
748 Failure in example: print range(15)
749 from line #0 of f
750 Expected: [0, 1, 2, ..., 14]
751 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
752 (1, 1)
753
754 >>> # With the flag:
755 >>> test = doctest.DocTestFinder().find(f)[0]
756 >>> flags = doctest.ELLIPSIS
757 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
758 (0, 1)
759
760The UNIFIED_DIFF flag causes failures that involve multi-line expected
761and actual outputs to be displayed using a unified diff:
762
763 >>> def f(x):
764 ... r'''
765 ... >>> print '\n'.join('abcdefg')
766 ... a
767 ... B
768 ... c
769 ... d
770 ... f
771 ... g
772 ... h
773 ... '''
774
775 >>> # Without the flag:
776 >>> test = doctest.DocTestFinder().find(f)[0]
777 >>> doctest.DocTestRunner(verbose=False).run(test)
778 **********************************************************************
779 Failure in example: print '\n'.join('abcdefg')
780 from line #1 of f
781 Expected:
782 a
783 B
784 c
785 d
786 f
787 g
788 h
789 Got:
790 a
791 b
792 c
793 d
794 e
795 f
796 g
797 (1, 1)
798
799 >>> # With the flag:
800 >>> test = doctest.DocTestFinder().find(f)[0]
801 >>> flags = doctest.UNIFIED_DIFF
802 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
803 **********************************************************************
804 Failure in example: print '\n'.join('abcdefg')
805 from line #1 of f
806 Differences (unified diff):
807 --- Expected
808 +++ Got
809 @@ -1,8 +1,8 @@
810 a
811 -B
812 +b
813 c
814 d
815 +e
816 f
817 g
818 -h
819 <BLANKLINE>
820 (1, 1)
821
822The CONTEXT_DIFF flag causes failures that involve multi-line expected
823and actual outputs to be displayed using a context diff:
824
825 >>> # Reuse f() from the UNIFIED_DIFF example, above.
826 >>> test = doctest.DocTestFinder().find(f)[0]
827 >>> flags = doctest.CONTEXT_DIFF
828 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
829 **********************************************************************
830 Failure in example: print '\n'.join('abcdefg')
831 from line #1 of f
832 Differences (context diff):
833 *** Expected
834 --- Got
835 ***************
836 *** 1,8 ****
837 a
838 ! B
839 c
840 d
841 f
842 g
843 - h
844 <BLANKLINE>
845 --- 1,8 ----
846 a
847 ! b
848 c
849 d
850 + e
851 f
852 g
853 <BLANKLINE>
854 (1, 1)
855"""
856 def option_directives(): r"""
857Tests of `DocTestRunner`'s option directive mechanism.
858
Edward Loper74bca7a2004-08-12 02:27:44 +0000859Option directives can be used to turn option flags on or off for a
860single example. To turn an option on for an example, follow that
861example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +0000862
863 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +0000864 ... >>> print range(10) # should fail: no ellipsis
865 ... [0, 1, ..., 9]
866 ...
867 ... >>> print range(10) # doctest: +ELLIPSIS
868 ... [0, 1, ..., 9]
869 ... '''
870 >>> test = doctest.DocTestFinder().find(f)[0]
871 >>> doctest.DocTestRunner(verbose=False).run(test)
872 **********************************************************************
873 Failure in example: print range(10) # should fail: no ellipsis
874 from line #1 of f
875 Expected: [0, 1, ..., 9]
876 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
877 (1, 2)
878
879To turn an option off for an example, follow that example with a
880comment of the form ``# doctest: -OPTION``:
881
882 >>> def f(x): r'''
883 ... >>> print range(10)
884 ... [0, 1, ..., 9]
885 ...
886 ... >>> # should fail: no ellipsis
887 ... >>> print range(10) # doctest: -ELLIPSIS
888 ... [0, 1, ..., 9]
889 ... '''
890 >>> test = doctest.DocTestFinder().find(f)[0]
891 >>> doctest.DocTestRunner(verbose=False,
892 ... optionflags=doctest.ELLIPSIS).run(test)
893 **********************************************************************
894 Failure in example: print range(10) # doctest: -ELLIPSIS
895 from line #6 of f
896 Expected: [0, 1, ..., 9]
897 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
898 (1, 2)
899
900Option directives affect only the example that they appear with; they
901do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +0000902
Edward Loper74bca7a2004-08-12 02:27:44 +0000903 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +0000904 ... >>> print range(10) # Should fail: no ellipsis
905 ... [0, 1, ..., 9]
906 ...
Edward Loper74bca7a2004-08-12 02:27:44 +0000907 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000908 ... [0, 1, ..., 9]
909 ...
Tim Peters8485b562004-08-04 18:46:34 +0000910 ... >>> print range(10) # Should fail: no ellipsis
911 ... [0, 1, ..., 9]
912 ... '''
913 >>> test = doctest.DocTestFinder().find(f)[0]
914 >>> doctest.DocTestRunner(verbose=False).run(test)
915 **********************************************************************
916 Failure in example: print range(10) # Should fail: no ellipsis
917 from line #1 of f
918 Expected: [0, 1, ..., 9]
919 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
920 **********************************************************************
921 Failure in example: print range(10) # Should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +0000922 from line #7 of f
Tim Peters8485b562004-08-04 18:46:34 +0000923 Expected: [0, 1, ..., 9]
924 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
925 (2, 3)
926
Edward Loper74bca7a2004-08-12 02:27:44 +0000927Multiple options may be modified by a single option directive. They
928may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +0000929
930 >>> def f(x): r'''
931 ... >>> print range(10) # Should fail
932 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +0000933 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +0000934 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +0000935 ... [0, 1, ..., 9]
936 ... '''
937 >>> test = doctest.DocTestFinder().find(f)[0]
938 >>> doctest.DocTestRunner(verbose=False).run(test)
939 **********************************************************************
940 Failure in example: print range(10) # Should fail
941 from line #1 of f
942 Expected: [0, 1, ..., 9]
943 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
944 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +0000945
946 >>> def f(x): r'''
947 ... >>> print range(10) # Should fail
948 ... [0, 1, ..., 9]
949 ... >>> print range(10) # Should succeed
950 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
951 ... [0, 1, ..., 9]
952 ... '''
953 >>> test = doctest.DocTestFinder().find(f)[0]
954 >>> doctest.DocTestRunner(verbose=False).run(test)
955 **********************************************************************
956 Failure in example: print range(10) # Should fail
957 from line #1 of f
958 Expected: [0, 1, ..., 9]
959 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
960 (1, 2)
961
962 >>> def f(x): r'''
963 ... >>> print range(10) # Should fail
964 ... [0, 1, ..., 9]
965 ... >>> print range(10) # Should succeed
966 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
967 ... [0, 1, ..., 9]
968 ... '''
969 >>> test = doctest.DocTestFinder().find(f)[0]
970 >>> doctest.DocTestRunner(verbose=False).run(test)
971 **********************************************************************
972 Failure in example: print range(10) # Should fail
973 from line #1 of f
974 Expected: [0, 1, ..., 9]
975 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
976 (1, 2)
977
978The option directive may be put on the line following the source, as
979long as a continuation prompt is used:
980
981 >>> def f(x): r'''
982 ... >>> print range(10)
983 ... ... # doctest: +ELLIPSIS
984 ... [0, 1, ..., 9]
985 ... '''
986 >>> test = doctest.DocTestFinder().find(f)[0]
987 >>> doctest.DocTestRunner(verbose=False).run(test)
988 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000989
Edward Loper74bca7a2004-08-12 02:27:44 +0000990For examples with multi-line source, the option directive may appear
991at the end of any line:
992
993 >>> def f(x): r'''
994 ... >>> for x in range(10): # doctest: +ELLIPSIS
995 ... ... print x,
996 ... 0 1 2 ... 9
997 ...
998 ... >>> for x in range(10):
999 ... ... print x, # doctest: +ELLIPSIS
1000 ... 0 1 2 ... 9
1001 ... '''
1002 >>> test = doctest.DocTestFinder().find(f)[0]
1003 >>> doctest.DocTestRunner(verbose=False).run(test)
1004 (0, 2)
1005
1006If more than one line of an example with multi-line source has an
1007option directive, then they are combined:
1008
1009 >>> def f(x): r'''
1010 ... Should fail (option directive not on the last line):
1011 ... >>> for x in range(10): # doctest: +ELLIPSIS
1012 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1013 ... 0 1 2...9
1014 ... '''
1015 >>> test = doctest.DocTestFinder().find(f)[0]
1016 >>> doctest.DocTestRunner(verbose=False).run(test)
1017 (0, 1)
1018
1019It is an error to have a comment of the form ``# doctest:`` that is
1020*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1021``OPTION`` is an option that has been registered with
1022`register_option`:
1023
1024 >>> # Error: Option not registered
1025 >>> s = '>>> print 12 #doctest: +BADOPTION'
1026 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1027 Traceback (most recent call last):
1028 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1029
1030 >>> # Error: No + or - prefix
1031 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1032 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1033 Traceback (most recent call last):
1034 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1035
1036It is an error to use an option directive on a line that contains no
1037source:
1038
1039 >>> s = '>>> # doctest: +ELLIPSIS'
1040 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1041 Traceback (most recent call last):
1042 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 +00001043"""
1044
1045def test_testsource(): r"""
1046Unit tests for `testsource()`.
1047
1048The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001049test with that name in that module, and converts it to a script. The
1050example code is converted to regular Python code. The surrounding
1051words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001052
1053 >>> import test.test_doctest
1054 >>> name = 'test.test_doctest.sample_func'
1055 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001056 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001057 #
Tim Peters8485b562004-08-04 18:46:34 +00001058 print sample_func(22)
1059 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001060 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001061 #
Edward Lopera5db6002004-08-12 02:41:30 +00001062 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001063
1064 >>> name = 'test.test_doctest.SampleNewStyleClass'
1065 >>> print doctest.testsource(test.test_doctest, name)
1066 print '1\n2\n3'
1067 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001068 ## 1
1069 ## 2
1070 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001071
1072 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1073 >>> print doctest.testsource(test.test_doctest, name)
1074 print SampleClass.a_classmethod(10)
1075 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001076 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001077 print SampleClass(0).a_classmethod(10)
1078 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001079 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001080"""
1081
1082def test_debug(): r"""
1083
1084Create a docstring that we want to debug:
1085
1086 >>> s = '''
1087 ... >>> x = 12
1088 ... >>> print x
1089 ... 12
1090 ... '''
1091
1092Create some fake stdin input, to feed to the debugger:
1093
1094 >>> import tempfile
1095 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1096 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1097 >>> fake_stdin.seek(0)
1098 >>> real_stdin = sys.stdin
1099 >>> sys.stdin = fake_stdin
1100
1101Run the debugger on the docstring, and then restore sys.stdin.
1102
Tim Peters8485b562004-08-04 18:46:34 +00001103 >>> try:
1104 ... doctest.debug_src(s)
1105 ... finally:
1106 ... sys.stdin = real_stdin
1107 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001108 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001109 > <string>(1)?()
1110 (Pdb) 12
1111 --Return--
1112 > <string>(1)?()->None
1113 (Pdb) 12
1114 (Pdb)
1115
1116"""
1117
Jim Fulton356fd192004-08-09 11:34:47 +00001118def test_pdb_set_trace():
1119 r"""Using pdb.set_trace from a doctest
1120
Tim Peters413ced62004-08-09 15:43:47 +00001121 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001122 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001123 you use it. The doctest module changes sys.stdout so that it can
1124 capture program output. It also temporarily replaces pdb.set_trace
1125 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001126 see debugger output.
1127
1128 >>> doc = '''
1129 ... >>> x = 42
1130 ... >>> import pdb; pdb.set_trace()
1131 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001132 >>> parser = doctest.DocTestParser()
1133 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001134 >>> runner = doctest.DocTestRunner(verbose=False)
1135
1136 To demonstrate this, we'll create a fake standard input that
1137 captures our debugger input:
1138
1139 >>> import tempfile
1140 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1141 >>> fake_stdin.write('\n'.join([
1142 ... 'up', # up out of pdb.set_trace
1143 ... 'up', # up again to get out of our wrapper
1144 ... 'print x', # print data defined by the example
1145 ... 'continue', # stop debugging
1146 ... '']))
1147 >>> fake_stdin.seek(0)
1148 >>> real_stdin = sys.stdin
1149 >>> sys.stdin = fake_stdin
1150
Edward Loper74bca7a2004-08-12 02:27:44 +00001151 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001152 --Return--
1153 > ...set_trace()->None
1154 -> Pdb().set_trace()
1155 (Pdb) > ...set_trace()
1156 -> real_pdb_set_trace()
1157 (Pdb) > <string>(1)?()
1158 (Pdb) 42
1159 (Pdb) (0, 2)
1160
1161 >>> sys.stdin = real_stdin
1162 >>> fake_stdin.close()
1163
1164 You can also put pdb.set_trace in a function called from a test:
1165
1166 >>> def calls_set_trace():
1167 ... y=2
1168 ... import pdb; pdb.set_trace()
1169
1170 >>> doc = '''
1171 ... >>> x=1
1172 ... >>> calls_set_trace()
1173 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001174 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001175 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1176 >>> fake_stdin.write('\n'.join([
1177 ... 'up', # up out of pdb.set_trace
1178 ... 'up', # up again to get out of our wrapper
1179 ... 'print y', # print data defined in the function
1180 ... 'up', # out of function
1181 ... 'print x', # print data defined by the example
1182 ... 'continue', # stop debugging
1183 ... '']))
1184 >>> fake_stdin.seek(0)
1185 >>> real_stdin = sys.stdin
1186 >>> sys.stdin = fake_stdin
1187
Edward Loper74bca7a2004-08-12 02:27:44 +00001188 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001189 --Return--
1190 > ...set_trace()->None
1191 -> Pdb().set_trace()
1192 (Pdb) ...set_trace()
1193 -> real_pdb_set_trace()
1194 (Pdb) > <string>(3)calls_set_trace()
1195 (Pdb) 2
1196 (Pdb) > <string>(1)?()
1197 (Pdb) 1
1198 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001199 """
1200
Tim Peters19397e52004-08-06 22:02:59 +00001201def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001202 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001203
1204 We create a Suite by providing a module. A module can be provided
1205 by passing a module object:
1206
1207 >>> import unittest
1208 >>> import test.sample_doctest
1209 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1210 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001211 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001212
1213 We can also supply the module by name:
1214
1215 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1216 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001217 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001218
1219 We can use the current module:
1220
1221 >>> suite = test.sample_doctest.test_suite()
1222 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001223 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001224
1225 We can supply global variables. If we pass globs, they will be
1226 used instead of the module globals. Here we'll pass an empty
1227 globals, triggering an extra error:
1228
1229 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1230 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001231 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001232
1233 Alternatively, we can provide extra globals. Here we'll make an
1234 error go away by providing an extra global variable:
1235
1236 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1237 ... extraglobs={'y': 1})
1238 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001239 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001240
1241 You can pass option flags. Here we'll cause an extra error
1242 by disabling the blank-line feature:
1243
1244 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001245 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001246 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001247 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001248
Tim Peters1e277ee2004-08-07 05:37:52 +00001249 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001250
1251 >>> def setUp():
1252 ... import test.test_doctest
1253 ... test.test_doctest.sillySetup = True
1254
1255 >>> def tearDown():
1256 ... import test.test_doctest
1257 ... del test.test_doctest.sillySetup
1258
1259 Here, we installed a silly variable that the test expects:
1260
1261 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1262 ... setUp=setUp, tearDown=tearDown)
1263 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001264 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001265
1266 But the tearDown restores sanity:
1267
1268 >>> import test.test_doctest
1269 >>> test.test_doctest.sillySetup
1270 Traceback (most recent call last):
1271 ...
1272 AttributeError: 'module' object has no attribute 'sillySetup'
1273
1274 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001275 use a custom test_finder to to run just the test named bar.
1276 However, the test in the module docstring, and the two tests
1277 in the module __test__ dict, aren't filtered, so we actually
1278 run three tests besides bar's. The filtering mechanisms are
1279 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001280
1281 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001282 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001283 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1284 ... test_finder=finder)
1285 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001286 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001287 """
1288
1289def test_DocFileSuite():
1290 """We can test tests found in text files using a DocFileSuite.
1291
1292 We create a suite by providing the names of one or more text
1293 files that include examples:
1294
1295 >>> import unittest
1296 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1297 ... 'test_doctest2.txt')
1298 >>> suite.run(unittest.TestResult())
1299 <unittest.TestResult run=2 errors=0 failures=2>
1300
1301 The test files are looked for in the directory containing the
1302 calling module. A package keyword argument can be provided to
1303 specify a different relative location.
1304
1305 >>> import unittest
1306 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1307 ... 'test_doctest2.txt',
1308 ... package='test')
1309 >>> suite.run(unittest.TestResult())
1310 <unittest.TestResult run=2 errors=0 failures=2>
1311
1312 Note that '/' should be used as a path separator. It will be
1313 converted to a native separator at run time:
1314
1315
1316 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1317 >>> suite.run(unittest.TestResult())
1318 <unittest.TestResult run=1 errors=0 failures=1>
1319
1320 You can specify initial global variables:
1321
1322 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1323 ... 'test_doctest2.txt',
1324 ... globs={'favorite_color': 'blue'})
1325 >>> suite.run(unittest.TestResult())
1326 <unittest.TestResult run=2 errors=0 failures=1>
1327
1328 In this case, we supplied a missing favorite color. You can
1329 provide doctest options:
1330
1331 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1332 ... 'test_doctest2.txt',
1333 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1334 ... globs={'favorite_color': 'blue'})
1335 >>> suite.run(unittest.TestResult())
1336 <unittest.TestResult run=2 errors=0 failures=2>
1337
1338 And, you can provide setUp and tearDown functions:
1339
1340 You can supply setUp and teatDoen functions:
1341
1342 >>> def setUp():
1343 ... import test.test_doctest
1344 ... test.test_doctest.sillySetup = True
1345
1346 >>> def tearDown():
1347 ... import test.test_doctest
1348 ... del test.test_doctest.sillySetup
1349
1350 Here, we installed a silly variable that the test expects:
1351
1352 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1353 ... 'test_doctest2.txt',
1354 ... setUp=setUp, tearDown=tearDown)
1355 >>> suite.run(unittest.TestResult())
1356 <unittest.TestResult run=2 errors=0 failures=1>
1357
1358 But the tearDown restores sanity:
1359
1360 >>> import test.test_doctest
1361 >>> test.test_doctest.sillySetup
1362 Traceback (most recent call last):
1363 ...
1364 AttributeError: 'module' object has no attribute 'sillySetup'
1365
1366 """
1367
1368
Tim Peters8485b562004-08-04 18:46:34 +00001369######################################################################
1370## Main
1371######################################################################
1372
1373def test_main():
1374 # Check the doctest cases in doctest itself:
1375 test_support.run_doctest(doctest, verbosity=True)
1376 # Check the doctest cases defined here:
1377 from test import test_doctest
1378 test_support.run_doctest(test_doctest, verbosity=True)
1379
1380import trace, sys, re, StringIO
1381def test_coverage(coverdir):
1382 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1383 trace=0, count=1)
1384 tracer.run('reload(doctest); test_main()')
1385 r = tracer.results()
1386 print 'Writing coverage results...'
1387 r.write_results(show_missing=True, summary=True,
1388 coverdir=coverdir)
1389
1390if __name__ == '__main__':
1391 if '-c' in sys.argv:
1392 test_coverage('/tmp/doctest.cover')
1393 else:
1394 test_main()