blob: 977ade7eaedddfac3884a2593724e3e2e4331f2f [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 Loper74bca7a2004-08-12 02:27:44 +0000272
273 >>> print tests # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000274 [<DocTest sample_func from ...:12 (1 example)>]
Edward Loper74bca7a2004-08-12 02:27:44 +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)
623 **********************************************************************
624 Failure in example: raise ValueError, 'message'
625 from line #1 of f
626 Expected:
627 Traceback (most recent call last):
628 ValueError: wrong message
629 Got:
630 Traceback (most recent call last):
631 ValueError: message
632 (1, 1)
633
634If an exception is raised but not expected, then it is reported as an
635unexpected exception:
636
Tim Peters8485b562004-08-04 18:46:34 +0000637 >>> def f(x):
638 ... r'''
639 ... >>> 1/0
640 ... 0
641 ... '''
642 >>> test = doctest.DocTestFinder().find(f)[0]
643 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000644 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000645 **********************************************************************
646 Failure in example: 1/0
647 from line #1 of f
648 Exception raised:
649 Traceback (most recent call last):
650 ...
651 ZeroDivisionError: integer division or modulo by zero
652 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000653"""
654 def optionflags(): r"""
655Tests of `DocTestRunner`'s option flag handling.
656
657Several option flags can be used to customize the behavior of the test
658runner. These are defined as module constants in doctest, and passed
659to the DocTestRunner constructor (multiple constants should be or-ed
660together).
661
662The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
663and 1/0:
664
665 >>> def f(x):
666 ... '>>> True\n1\n'
667
668 >>> # Without the flag:
669 >>> test = doctest.DocTestFinder().find(f)[0]
670 >>> doctest.DocTestRunner(verbose=False).run(test)
671 (0, 1)
672
673 >>> # With the flag:
674 >>> test = doctest.DocTestFinder().find(f)[0]
675 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
676 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
677 **********************************************************************
678 Failure in example: True
679 from line #0 of f
680 Expected: 1
681 Got: True
682 (1, 1)
683
684The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
685and the '<BLANKLINE>' marker:
686
687 >>> def f(x):
688 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
689
690 >>> # Without the flag:
691 >>> test = doctest.DocTestFinder().find(f)[0]
692 >>> doctest.DocTestRunner(verbose=False).run(test)
693 (0, 1)
694
695 >>> # With the flag:
696 >>> test = doctest.DocTestFinder().find(f)[0]
697 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
698 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
699 **********************************************************************
700 Failure in example: print "a\n\nb"
701 from line #0 of f
702 Expected:
703 a
704 <BLANKLINE>
705 b
706 Got:
707 a
708 <BLANKLINE>
709 b
710 (1, 1)
711
712The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
713treated as equal:
714
715 >>> def f(x):
716 ... '>>> print 1, 2, 3\n 1 2\n 3'
717
718 >>> # Without the flag:
719 >>> test = doctest.DocTestFinder().find(f)[0]
720 >>> doctest.DocTestRunner(verbose=False).run(test)
721 **********************************************************************
722 Failure in example: print 1, 2, 3
723 from line #0 of f
724 Expected:
725 1 2
726 3
727 Got: 1 2 3
728 (1, 1)
729
730 >>> # With the flag:
731 >>> test = doctest.DocTestFinder().find(f)[0]
732 >>> flags = doctest.NORMALIZE_WHITESPACE
733 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
734 (0, 1)
735
736The ELLIPSIS flag causes ellipsis marker ("...") in the expected
737output to match any substring in the actual output:
738
739 >>> def f(x):
740 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
741
742 >>> # Without the flag:
743 >>> test = doctest.DocTestFinder().find(f)[0]
744 >>> doctest.DocTestRunner(verbose=False).run(test)
745 **********************************************************************
746 Failure in example: print range(15)
747 from line #0 of f
748 Expected: [0, 1, 2, ..., 14]
749 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
750 (1, 1)
751
752 >>> # With the flag:
753 >>> test = doctest.DocTestFinder().find(f)[0]
754 >>> flags = doctest.ELLIPSIS
755 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
756 (0, 1)
757
758The UNIFIED_DIFF flag causes failures that involve multi-line expected
759and actual outputs to be displayed using a unified diff:
760
761 >>> def f(x):
762 ... r'''
763 ... >>> print '\n'.join('abcdefg')
764 ... a
765 ... B
766 ... c
767 ... d
768 ... f
769 ... g
770 ... h
771 ... '''
772
773 >>> # Without the flag:
774 >>> test = doctest.DocTestFinder().find(f)[0]
775 >>> doctest.DocTestRunner(verbose=False).run(test)
776 **********************************************************************
777 Failure in example: print '\n'.join('abcdefg')
778 from line #1 of f
779 Expected:
780 a
781 B
782 c
783 d
784 f
785 g
786 h
787 Got:
788 a
789 b
790 c
791 d
792 e
793 f
794 g
795 (1, 1)
796
797 >>> # With the flag:
798 >>> test = doctest.DocTestFinder().find(f)[0]
799 >>> flags = doctest.UNIFIED_DIFF
800 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
801 **********************************************************************
802 Failure in example: print '\n'.join('abcdefg')
803 from line #1 of f
804 Differences (unified diff):
805 --- Expected
806 +++ Got
807 @@ -1,8 +1,8 @@
808 a
809 -B
810 +b
811 c
812 d
813 +e
814 f
815 g
816 -h
817 <BLANKLINE>
818 (1, 1)
819
820The CONTEXT_DIFF flag causes failures that involve multi-line expected
821and actual outputs to be displayed using a context diff:
822
823 >>> # Reuse f() from the UNIFIED_DIFF example, above.
824 >>> test = doctest.DocTestFinder().find(f)[0]
825 >>> flags = doctest.CONTEXT_DIFF
826 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
827 **********************************************************************
828 Failure in example: print '\n'.join('abcdefg')
829 from line #1 of f
830 Differences (context diff):
831 *** Expected
832 --- Got
833 ***************
834 *** 1,8 ****
835 a
836 ! B
837 c
838 d
839 f
840 g
841 - h
842 <BLANKLINE>
843 --- 1,8 ----
844 a
845 ! b
846 c
847 d
848 + e
849 f
850 g
851 <BLANKLINE>
852 (1, 1)
853"""
854 def option_directives(): r"""
855Tests of `DocTestRunner`'s option directive mechanism.
856
Edward Loper74bca7a2004-08-12 02:27:44 +0000857Option directives can be used to turn option flags on or off for a
858single example. To turn an option on for an example, follow that
859example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +0000860
861 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +0000862 ... >>> print range(10) # should fail: no ellipsis
863 ... [0, 1, ..., 9]
864 ...
865 ... >>> print range(10) # doctest: +ELLIPSIS
866 ... [0, 1, ..., 9]
867 ... '''
868 >>> test = doctest.DocTestFinder().find(f)[0]
869 >>> doctest.DocTestRunner(verbose=False).run(test)
870 **********************************************************************
871 Failure in example: print range(10) # should fail: no ellipsis
872 from line #1 of f
873 Expected: [0, 1, ..., 9]
874 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
875 (1, 2)
876
877To turn an option off for an example, follow that example with a
878comment of the form ``# doctest: -OPTION``:
879
880 >>> def f(x): r'''
881 ... >>> print range(10)
882 ... [0, 1, ..., 9]
883 ...
884 ... >>> # should fail: no ellipsis
885 ... >>> print range(10) # doctest: -ELLIPSIS
886 ... [0, 1, ..., 9]
887 ... '''
888 >>> test = doctest.DocTestFinder().find(f)[0]
889 >>> doctest.DocTestRunner(verbose=False,
890 ... optionflags=doctest.ELLIPSIS).run(test)
891 **********************************************************************
892 Failure in example: print range(10) # doctest: -ELLIPSIS
893 from line #6 of f
894 Expected: [0, 1, ..., 9]
895 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
896 (1, 2)
897
898Option directives affect only the example that they appear with; they
899do not change the options for surrounding examples:
900
901 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +0000902 ... >>> print range(10) # Should fail: no ellipsis
903 ... [0, 1, ..., 9]
904 ...
Edward Loper74bca7a2004-08-12 02:27:44 +0000905 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000906 ... [0, 1, ..., 9]
907 ...
Tim Peters8485b562004-08-04 18:46:34 +0000908 ... >>> print range(10) # Should fail: no ellipsis
909 ... [0, 1, ..., 9]
910 ... '''
911 >>> test = doctest.DocTestFinder().find(f)[0]
912 >>> doctest.DocTestRunner(verbose=False).run(test)
913 **********************************************************************
914 Failure in example: print range(10) # Should fail: no ellipsis
915 from line #1 of f
916 Expected: [0, 1, ..., 9]
917 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
918 **********************************************************************
919 Failure in example: print range(10) # Should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +0000920 from line #7 of f
Tim Peters8485b562004-08-04 18:46:34 +0000921 Expected: [0, 1, ..., 9]
922 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
923 (2, 3)
924
Edward Loper74bca7a2004-08-12 02:27:44 +0000925Multiple options may be modified by a single option directive. They
926may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +0000927
928 >>> def f(x): r'''
929 ... >>> print range(10) # Should fail
930 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +0000931 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +0000932 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +0000933 ... [0, 1, ..., 9]
934 ... '''
935 >>> test = doctest.DocTestFinder().find(f)[0]
936 >>> doctest.DocTestRunner(verbose=False).run(test)
937 **********************************************************************
938 Failure in example: print range(10) # Should fail
939 from line #1 of f
940 Expected: [0, 1, ..., 9]
941 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
942 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +0000943
944 >>> def f(x): r'''
945 ... >>> print range(10) # Should fail
946 ... [0, 1, ..., 9]
947 ... >>> print range(10) # Should succeed
948 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
949 ... [0, 1, ..., 9]
950 ... '''
951 >>> test = doctest.DocTestFinder().find(f)[0]
952 >>> doctest.DocTestRunner(verbose=False).run(test)
953 **********************************************************************
954 Failure in example: print range(10) # Should fail
955 from line #1 of f
956 Expected: [0, 1, ..., 9]
957 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
958 (1, 2)
959
960 >>> def f(x): r'''
961 ... >>> print range(10) # Should fail
962 ... [0, 1, ..., 9]
963 ... >>> print range(10) # Should succeed
964 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
965 ... [0, 1, ..., 9]
966 ... '''
967 >>> test = doctest.DocTestFinder().find(f)[0]
968 >>> doctest.DocTestRunner(verbose=False).run(test)
969 **********************************************************************
970 Failure in example: print range(10) # Should fail
971 from line #1 of f
972 Expected: [0, 1, ..., 9]
973 Got: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
974 (1, 2)
975
976The option directive may be put on the line following the source, as
977long as a continuation prompt is used:
978
979 >>> def f(x): r'''
980 ... >>> print range(10)
981 ... ... # doctest: +ELLIPSIS
982 ... [0, 1, ..., 9]
983 ... '''
984 >>> test = doctest.DocTestFinder().find(f)[0]
985 >>> doctest.DocTestRunner(verbose=False).run(test)
986 (0, 1)
987
988For examples with multi-line source, the option directive may appear
989at the end of any line:
990
991 >>> def f(x): r'''
992 ... >>> for x in range(10): # doctest: +ELLIPSIS
993 ... ... print x,
994 ... 0 1 2 ... 9
995 ...
996 ... >>> for x in range(10):
997 ... ... print x, # doctest: +ELLIPSIS
998 ... 0 1 2 ... 9
999 ... '''
1000 >>> test = doctest.DocTestFinder().find(f)[0]
1001 >>> doctest.DocTestRunner(verbose=False).run(test)
1002 (0, 2)
1003
1004If more than one line of an example with multi-line source has an
1005option directive, then they are combined:
1006
1007 >>> def f(x): r'''
1008 ... Should fail (option directive not on the last line):
1009 ... >>> for x in range(10): # doctest: +ELLIPSIS
1010 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1011 ... 0 1 2...9
1012 ... '''
1013 >>> test = doctest.DocTestFinder().find(f)[0]
1014 >>> doctest.DocTestRunner(verbose=False).run(test)
1015 (0, 1)
1016
1017It is an error to have a comment of the form ``# doctest:`` that is
1018*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1019``OPTION`` is an option that has been registered with
1020`register_option`:
1021
1022 >>> # Error: Option not registered
1023 >>> s = '>>> print 12 #doctest: +BADOPTION'
1024 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1025 Traceback (most recent call last):
1026 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1027
1028 >>> # Error: No + or - prefix
1029 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1030 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1031 Traceback (most recent call last):
1032 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1033
1034It is an error to use an option directive on a line that contains no
1035source:
1036
1037 >>> s = '>>> # doctest: +ELLIPSIS'
1038 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1039 Traceback (most recent call last):
1040 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 +00001041"""
1042
1043def test_testsource(): r"""
1044Unit tests for `testsource()`.
1045
1046The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001047test with that name in that module, and converts it to a script. The
1048example code is converted to regular Python code. The surrounding
1049words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001050
1051 >>> import test.test_doctest
1052 >>> name = 'test.test_doctest.sample_func'
1053 >>> print doctest.testsource(test.test_doctest, name)
Tim Peters19397e52004-08-06 22:02:59 +00001054 # Blah blah
1055 #
Tim Peters8485b562004-08-04 18:46:34 +00001056 print sample_func(22)
1057 # Expected:
1058 # 44
Tim Peters19397e52004-08-06 22:02:59 +00001059 #
1060 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001061
1062 >>> name = 'test.test_doctest.SampleNewStyleClass'
1063 >>> print doctest.testsource(test.test_doctest, name)
1064 print '1\n2\n3'
1065 # Expected:
1066 # 1
1067 # 2
1068 # 3
1069
1070 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1071 >>> print doctest.testsource(test.test_doctest, name)
1072 print SampleClass.a_classmethod(10)
1073 # Expected:
1074 # 12
1075 print SampleClass(0).a_classmethod(10)
1076 # Expected:
1077 # 12
1078"""
1079
1080def test_debug(): r"""
1081
1082Create a docstring that we want to debug:
1083
1084 >>> s = '''
1085 ... >>> x = 12
1086 ... >>> print x
1087 ... 12
1088 ... '''
1089
1090Create some fake stdin input, to feed to the debugger:
1091
1092 >>> import tempfile
1093 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1094 >>> fake_stdin.write('\n'.join(['next', 'print x', 'continue', '']))
1095 >>> fake_stdin.seek(0)
1096 >>> real_stdin = sys.stdin
1097 >>> sys.stdin = fake_stdin
1098
1099Run the debugger on the docstring, and then restore sys.stdin.
1100
Tim Peters8485b562004-08-04 18:46:34 +00001101 >>> try:
1102 ... doctest.debug_src(s)
1103 ... finally:
1104 ... sys.stdin = real_stdin
1105 ... fake_stdin.close()
Edward Loper74bca7a2004-08-12 02:27:44 +00001106 ... # doctest: +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001107 > <string>(1)?()
1108 (Pdb) 12
1109 --Return--
1110 > <string>(1)?()->None
1111 (Pdb) 12
1112 (Pdb)
1113
1114"""
1115
Jim Fulton356fd192004-08-09 11:34:47 +00001116def test_pdb_set_trace():
1117 r"""Using pdb.set_trace from a doctest
1118
Tim Peters413ced62004-08-09 15:43:47 +00001119 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001120 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001121 you use it. The doctest module changes sys.stdout so that it can
1122 capture program output. It also temporarily replaces pdb.set_trace
1123 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001124 see debugger output.
1125
1126 >>> doc = '''
1127 ... >>> x = 42
1128 ... >>> import pdb; pdb.set_trace()
1129 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001130 >>> parser = doctest.DocTestParser()
1131 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001132 >>> runner = doctest.DocTestRunner(verbose=False)
1133
1134 To demonstrate this, we'll create a fake standard input that
1135 captures our debugger input:
1136
1137 >>> import tempfile
1138 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1139 >>> fake_stdin.write('\n'.join([
1140 ... 'up', # up out of pdb.set_trace
1141 ... 'up', # up again to get out of our wrapper
1142 ... 'print x', # print data defined by the example
1143 ... 'continue', # stop debugging
1144 ... '']))
1145 >>> fake_stdin.seek(0)
1146 >>> real_stdin = sys.stdin
1147 >>> sys.stdin = fake_stdin
1148
Edward Loper74bca7a2004-08-12 02:27:44 +00001149 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001150 --Return--
1151 > ...set_trace()->None
1152 -> Pdb().set_trace()
1153 (Pdb) > ...set_trace()
1154 -> real_pdb_set_trace()
1155 (Pdb) > <string>(1)?()
1156 (Pdb) 42
1157 (Pdb) (0, 2)
1158
1159 >>> sys.stdin = real_stdin
1160 >>> fake_stdin.close()
1161
1162 You can also put pdb.set_trace in a function called from a test:
1163
1164 >>> def calls_set_trace():
1165 ... y=2
1166 ... import pdb; pdb.set_trace()
1167
1168 >>> doc = '''
1169 ... >>> x=1
1170 ... >>> calls_set_trace()
1171 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001172 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001173 >>> fake_stdin = tempfile.TemporaryFile(mode='w+')
1174 >>> fake_stdin.write('\n'.join([
1175 ... 'up', # up out of pdb.set_trace
1176 ... 'up', # up again to get out of our wrapper
1177 ... 'print y', # print data defined in the function
1178 ... 'up', # out of function
1179 ... 'print x', # print data defined by the example
1180 ... 'continue', # stop debugging
1181 ... '']))
1182 >>> fake_stdin.seek(0)
1183 >>> real_stdin = sys.stdin
1184 >>> sys.stdin = fake_stdin
1185
Edward Loper74bca7a2004-08-12 02:27:44 +00001186 >>> runner.run(test) # doctest: +ELLIPSIS
Jim Fulton356fd192004-08-09 11:34:47 +00001187 --Return--
1188 > ...set_trace()->None
1189 -> Pdb().set_trace()
1190 (Pdb) ...set_trace()
1191 -> real_pdb_set_trace()
1192 (Pdb) > <string>(3)calls_set_trace()
1193 (Pdb) 2
1194 (Pdb) > <string>(1)?()
1195 (Pdb) 1
1196 (Pdb) (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001197 """
1198
Tim Peters19397e52004-08-06 22:02:59 +00001199def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001200 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001201
1202 We create a Suite by providing a module. A module can be provided
1203 by passing a module object:
1204
1205 >>> import unittest
1206 >>> import test.sample_doctest
1207 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1208 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001209 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001210
1211 We can also supply the module by name:
1212
1213 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1214 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001215 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001216
1217 We can use the current module:
1218
1219 >>> suite = test.sample_doctest.test_suite()
1220 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001221 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001222
1223 We can supply global variables. If we pass globs, they will be
1224 used instead of the module globals. Here we'll pass an empty
1225 globals, triggering an extra error:
1226
1227 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1228 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001229 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001230
1231 Alternatively, we can provide extra globals. Here we'll make an
1232 error go away by providing an extra global variable:
1233
1234 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1235 ... extraglobs={'y': 1})
1236 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001237 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001238
1239 You can pass option flags. Here we'll cause an extra error
1240 by disabling the blank-line feature:
1241
1242 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001243 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001244 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001245 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001246
Tim Peters1e277ee2004-08-07 05:37:52 +00001247 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001248
1249 >>> def setUp():
1250 ... import test.test_doctest
1251 ... test.test_doctest.sillySetup = True
1252
1253 >>> def tearDown():
1254 ... import test.test_doctest
1255 ... del test.test_doctest.sillySetup
1256
1257 Here, we installed a silly variable that the test expects:
1258
1259 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1260 ... setUp=setUp, tearDown=tearDown)
1261 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001262 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001263
1264 But the tearDown restores sanity:
1265
1266 >>> import test.test_doctest
1267 >>> test.test_doctest.sillySetup
1268 Traceback (most recent call last):
1269 ...
1270 AttributeError: 'module' object has no attribute 'sillySetup'
1271
1272 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001273 use a custom test_finder to to run just the test named bar.
1274 However, the test in the module docstring, and the two tests
1275 in the module __test__ dict, aren't filtered, so we actually
1276 run three tests besides bar's. The filtering mechanisms are
1277 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001278
1279 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001280 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001281 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1282 ... test_finder=finder)
1283 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001284 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001285 """
1286
1287def test_DocFileSuite():
1288 """We can test tests found in text files using a DocFileSuite.
1289
1290 We create a suite by providing the names of one or more text
1291 files that include examples:
1292
1293 >>> import unittest
1294 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1295 ... 'test_doctest2.txt')
1296 >>> suite.run(unittest.TestResult())
1297 <unittest.TestResult run=2 errors=0 failures=2>
1298
1299 The test files are looked for in the directory containing the
1300 calling module. A package keyword argument can be provided to
1301 specify a different relative location.
1302
1303 >>> import unittest
1304 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1305 ... 'test_doctest2.txt',
1306 ... package='test')
1307 >>> suite.run(unittest.TestResult())
1308 <unittest.TestResult run=2 errors=0 failures=2>
1309
1310 Note that '/' should be used as a path separator. It will be
1311 converted to a native separator at run time:
1312
1313
1314 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1315 >>> suite.run(unittest.TestResult())
1316 <unittest.TestResult run=1 errors=0 failures=1>
1317
1318 You can specify initial global variables:
1319
1320 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1321 ... 'test_doctest2.txt',
1322 ... globs={'favorite_color': 'blue'})
1323 >>> suite.run(unittest.TestResult())
1324 <unittest.TestResult run=2 errors=0 failures=1>
1325
1326 In this case, we supplied a missing favorite color. You can
1327 provide doctest options:
1328
1329 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1330 ... 'test_doctest2.txt',
1331 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1332 ... globs={'favorite_color': 'blue'})
1333 >>> suite.run(unittest.TestResult())
1334 <unittest.TestResult run=2 errors=0 failures=2>
1335
1336 And, you can provide setUp and tearDown functions:
1337
1338 You can supply setUp and teatDoen functions:
1339
1340 >>> def setUp():
1341 ... import test.test_doctest
1342 ... test.test_doctest.sillySetup = True
1343
1344 >>> def tearDown():
1345 ... import test.test_doctest
1346 ... del test.test_doctest.sillySetup
1347
1348 Here, we installed a silly variable that the test expects:
1349
1350 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1351 ... 'test_doctest2.txt',
1352 ... setUp=setUp, tearDown=tearDown)
1353 >>> suite.run(unittest.TestResult())
1354 <unittest.TestResult run=2 errors=0 failures=1>
1355
1356 But the tearDown restores sanity:
1357
1358 >>> import test.test_doctest
1359 >>> test.test_doctest.sillySetup
1360 Traceback (most recent call last):
1361 ...
1362 AttributeError: 'module' object has no attribute 'sillySetup'
1363
1364 """
1365
1366
Tim Peters8485b562004-08-04 18:46:34 +00001367######################################################################
1368## Main
1369######################################################################
1370
1371def test_main():
1372 # Check the doctest cases in doctest itself:
1373 test_support.run_doctest(doctest, verbosity=True)
1374 # Check the doctest cases defined here:
1375 from test import test_doctest
1376 test_support.run_doctest(test_doctest, verbosity=True)
1377
1378import trace, sys, re, StringIO
1379def test_coverage(coverdir):
1380 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1381 trace=0, count=1)
1382 tracer.run('reload(doctest); test_main()')
1383 r = tracer.results()
1384 print 'Writing coverage results...'
1385 r.write_results(show_missing=True, summary=True,
1386 coverdir=coverdir)
1387
1388if __name__ == '__main__':
1389 if '-c' in sys.argv:
1390 test_coverage('/tmp/doctest.cover')
1391 else:
1392 test_main()