Debian Codegraph @

Lib/test/test_doctest/test_doctest.py

raw
1 """
2 Test script for doctest.
3 """
4
5 from test import support
6 from test.support import import_helper
7 from test.support.pty_helper import FakeInput # used in doctests
8 import doctest
9 import functools
10 import os
11 import sys
12 import importlib
13 import importlib.abc
14 import importlib.util
15 import unittest
16 import tempfile
17 import types
18 import contextlib
19 import _colorize
20
21
22 def doctest_skip_if(condition):
23 def decorator(func):
24 if condition and support.HAVE_DOCSTRINGS:
25 func.__doc__ = ">>> pass # doctest: +SKIP"
26 return func
27 return decorator
28
29
30 # NOTE: There are some additional tests relating to interaction with
31 # zipimport in the test_zipimport_support test module.
32 # There are also related tests in `test_doctest2` module.
33
34 ######################################################################
35 ## Sample Objects (used by test cases)
36 ######################################################################
37
38 def sample_func(v):
39 """
40 Blah blah
41
42 >>> print(sample_func(22))
43 44
44
45 Yee ha!
46 """
47 return v+v
48
49 class SampleClass:
50 """
51 >>> print(1)
52 1
53
54 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
55 >>>
56 ...
57
58 Multiline example:
59 >>> sc = SampleClass(3)
60 >>> for i in range(10):
61 ... sc = sc.double()
62 ... print(' ', sc.get(), sep='', end='')
63 6 12 24 48 96 192 384 768 1536 3072
64 """
65 def __init__(self, val):
66 """
67 >>> print(SampleClass(12).get())
68 12
69 """
70 self.val = val
71
72 def double(self):
73 """
74 >>> print(SampleClass(12).double().get())
75 24
76 """
77 return SampleClass(self.val + self.val)
78
79 def get(self):
80 """
81 >>> print(SampleClass(-5).get())
82 -5
83 """
84 return self.val
85
86 def setter(self, val):
87 """
88 >>> s = SampleClass(-5)
89 >>> s.setter(1)
90 >>> print(s.val)
91 1
92 """
93 self.val = val
94
95 def a_staticmethod(v):
96 """
97 >>> print(SampleClass.a_staticmethod(10))
98 11
99 """
100 return v+1
101 a_staticmethod = staticmethod(a_staticmethod)
102
103 def a_classmethod(cls, v):
104 """
105 >>> print(SampleClass.a_classmethod(10))
106 12
107 >>> print(SampleClass(0).a_classmethod(10))
108 12
109 """
110 return v+2
111 a_classmethod = classmethod(a_classmethod)
112
113 a_property = property(get, setter, doc="""
114 >>> print(SampleClass(22).a_property)
115 22
116 """)
117
118 a_class_attribute = 42
119
120 @functools.cached_property
121 def a_cached_property(self):
122 """
123 >>> print(SampleClass(29).get())
124 29
125 """
126 return "hello"
127
128 class NestedClass:
129 """
130 >>> x = SampleClass.NestedClass(5)
131 >>> y = x.square()
132 >>> print(y.get())
133 25
134 """
135 def __init__(self, val=0):
136 """
137 >>> print(SampleClass.NestedClass().get())
138 0
139 """
140 self.val = val
141 def square(self):
142 return SampleClass.NestedClass(self.val*self.val)
143 def get(self):
144 return self.val
145
146 class SampleNewStyleClass(object):
147 r"""
148 >>> print('1\n2\n3')
149 1
150 2
151 3
152 """
153 def __init__(self, val):
154 """
155 >>> print(SampleNewStyleClass(12).get())
156 12
157 """
158 self.val = val
159
160 def double(self):
161 """
162 >>> print(SampleNewStyleClass(12).double().get())
163 24
164 """
165 return SampleNewStyleClass(self.val + self.val)
166
167 def get(self):
168 """
169 >>> print(SampleNewStyleClass(-5).get())
170 -5
171 """
172 return self.val
173
174 ######################################################################
175 ## Test Cases
176 ######################################################################
177
178 def test_Example(): r"""
179 Unit tests for the `Example` class.
180
181 Example is a simple container class that holds:
182 - `source`: A source string.
183 - `want`: An expected output string.
184 - `exc_msg`: An expected exception message string (or None if no
185 exception is expected).
186 - `lineno`: A line number (within the docstring).
187 - `indent`: The example's indentation in the input string.
188 - `options`: An option dictionary, mapping option flags to True or
189 False.
190
191 These attributes are set by the constructor. `source` and `want` are
192 required; the other attributes all have default values:
193
194 >>> example = doctest.Example('print(1)', '1\n')
195 >>> (example.source, example.want, example.exc_msg,
196 ... example.lineno, example.indent, example.options)
197 ('print(1)\n', '1\n', None, 0, 0, {})
198
199 The first three attributes (`source`, `want`, and `exc_msg`) may be
200 specified positionally; the remaining arguments should be specified as
201 keyword arguments:
202
203 >>> exc_msg = 'IndexError: pop from an empty list'
204 >>> example = doctest.Example('[].pop()', '', exc_msg,
205 ... lineno=5, indent=4,
206 ... options={doctest.ELLIPSIS: True})
207 >>> (example.source, example.want, example.exc_msg,
208 ... example.lineno, example.indent, example.options)
209 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
210
211 The constructor normalizes the `source` string to end in a newline:
212
213 Source spans a single line: no terminating newline.
214 >>> e = doctest.Example('print(1)', '1\n')
215 >>> e.source, e.want
216 ('print(1)\n', '1\n')
217
218 >>> e = doctest.Example('print(1)\n', '1\n')
219 >>> e.source, e.want
220 ('print(1)\n', '1\n')
221
222 Source spans multiple lines: require terminating newline.
223 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
224 >>> e.source, e.want
225 ('print(1);\nprint(2)\n', '1\n2\n')
226
227 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
228 >>> e.source, e.want
229 ('print(1);\nprint(2)\n', '1\n2\n')
230
231 Empty source string (which should never appear in real examples)
232 >>> e = doctest.Example('', '')
233 >>> e.source, e.want
234 ('\n', '')
235
236 The constructor normalizes the `want` string to end in a newline,
237 unless it's the empty string:
238
239 >>> e = doctest.Example('print(1)', '1\n')
240 >>> e.source, e.want
241 ('print(1)\n', '1\n')
242
243 >>> e = doctest.Example('print(1)', '1')
244 >>> e.source, e.want
245 ('print(1)\n', '1\n')
246
247 >>> e = doctest.Example('print', '')
248 >>> e.source, e.want
249 ('print\n', '')
250
251 The constructor normalizes the `exc_msg` string to end in a newline,
252 unless it's `None`:
253
254 Message spans one line
255 >>> exc_msg = 'IndexError: pop from an empty list'
256 >>> e = doctest.Example('[].pop()', '', exc_msg)
257 >>> e.exc_msg
258 'IndexError: pop from an empty list\n'
259
260 >>> exc_msg = 'IndexError: pop from an empty list\n'
261 >>> e = doctest.Example('[].pop()', '', exc_msg)
262 >>> e.exc_msg
263 'IndexError: pop from an empty list\n'
264
265 Message spans multiple lines
266 >>> exc_msg = 'ValueError: 1\n 2'
267 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
268 >>> e.exc_msg
269 'ValueError: 1\n 2\n'
270
271 >>> exc_msg = 'ValueError: 1\n 2\n'
272 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
273 >>> e.exc_msg
274 'ValueError: 1\n 2\n'
275
276 Empty (but non-None) exception message (which should never appear
277 in real examples)
278 >>> exc_msg = ''
279 >>> e = doctest.Example('raise X()', '', exc_msg)
280 >>> e.exc_msg
281 '\n'
282
283 Compare `Example`:
284 >>> example = doctest.Example('print 1', '1\n')
285 >>> same_example = doctest.Example('print 1', '1\n')
286 >>> other_example = doctest.Example('print 42', '42\n')
287 >>> example == same_example
288 True
289 >>> example != same_example
290 False
291 >>> hash(example) == hash(same_example)
292 True
293 >>> example == other_example
294 False
295 >>> example != other_example
296 True
297 """
298
299 def test_DocTest(): r"""
300 Unit tests for the `DocTest` class.
301
302 DocTest is a collection of examples, extracted from a docstring, along
303 with information about where the docstring comes from (a name,
304 filename, and line number). The docstring is parsed by the `DocTest`
305 constructor:
306
307 >>> docstring = '''
308 ... >>> print(12)
309 ... 12
310 ...
311 ... Non-example text.
312 ...
313 ... >>> print('another\\example')
314 ... another
315 ... example
316 ... '''
317 >>> globs = {} # globals to run the test in.
318 >>> parser = doctest.DocTestParser()
319 >>> test = parser.get_doctest(docstring, globs, 'some_test',
320 ... 'some_file', 20)
321 >>> print(test)
322 <DocTest some_test from some_file:20 (2 examples)>
323 >>> len(test.examples)
324 2
325 >>> e1, e2 = test.examples
326 >>> (e1.source, e1.want, e1.lineno)
327 ('print(12)\n', '12\n', 1)
328 >>> (e2.source, e2.want, e2.lineno)
329 ("print('another\\example')\n", 'another\nexample\n', 6)
330
331 Source information (name, filename, and line number) is available as
332 attributes on the doctest object:
333
334 >>> (test.name, test.filename, test.lineno)
335 ('some_test', 'some_file', 20)
336
337 The line number of an example within its containing file is found by
338 adding the line number of the example and the line number of its
339 containing test:
340
341 >>> test.lineno + e1.lineno
342 21
343 >>> test.lineno + e2.lineno
344 26
345
346 If the docstring contains inconsistent leading whitespace in the
347 expected output of an example, then `DocTest` will raise a ValueError:
348
349 >>> docstring = r'''
350 ... >>> print('bad\nindentation')
351 ... bad
352 ... indentation
353 ... '''
354 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
355 Traceback (most recent call last):
356 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
357
358 If the docstring contains inconsistent leading whitespace on
359 continuation lines, then `DocTest` will raise a ValueError:
360
361 >>> docstring = r'''
362 ... >>> print(('bad indentation',
363 ... ... 2))
364 ... ('bad', 'indentation')
365 ... '''
366 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
367 Traceback (most recent call last):
368 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
369
370 If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
371 will raise a ValueError:
372
373 >>> docstring = '>>>print(1)\n1'
374 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
375 Traceback (most recent call last):
376 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
377
378 If there's no blank space after a PS2 prompt ('...'), then `DocTest`
379 will raise a ValueError:
380
381 >>> docstring = '>>> if 1:\n...print(1)\n1'
382 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
383 Traceback (most recent call last):
384 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
385
386 Compare `DocTest`:
387
388 >>> docstring = '''
389 ... >>> print 12
390 ... 12
391 ... '''
392 >>> test = parser.get_doctest(docstring, globs, 'some_test',
393 ... 'some_test', 20)
394 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
395 ... 'some_test', 20)
396 >>> test == same_test
397 True
398 >>> test != same_test
399 False
400 >>> hash(test) == hash(same_test)
401 True
402 >>> docstring = '''
403 ... >>> print 42
404 ... 42
405 ... '''
406 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
407 ... 'other_file', 10)
408 >>> test == other_test
409 False
410 >>> test != other_test
411 True
412 >>> test < other_test
413 False
414 >>> other_test < test
415 True
416
417 Test comparison with lineno None on one side
418
419 >>> no_lineno = parser.get_doctest(docstring, globs, 'some_test',
420 ... 'some_test', None)
421 >>> test.lineno is None
422 False
423 >>> no_lineno.lineno is None
424 True
425 >>> test < no_lineno
426 False
427 >>> no_lineno < test
428 True
429
430 Compare `DocTestCase`:
431
432 >>> DocTestCase = doctest.DocTestCase
433 >>> test_case = DocTestCase(test)
434 >>> same_test_case = DocTestCase(same_test)
435 >>> other_test_case = DocTestCase(other_test)
436 >>> test_case == same_test_case
437 True
438 >>> test_case != same_test_case
439 False
440 >>> hash(test_case) == hash(same_test_case)
441 True
442 >>> test == other_test_case
443 False
444 >>> test != other_test_case
445 True
446
447 """
448
449 class test_DocTestFinder:
450 def basics(): r"""
451 Unit tests for the `DocTestFinder` class.
452
453 DocTestFinder is used to extract DocTests from an object's docstring
454 and the docstrings of its contained objects. It can be used with
455 modules, functions, classes, methods, staticmethods, classmethods, and
456 properties.
457
458 Finding Tests in Functions
459 ~~~~~~~~~~~~~~~~~~~~~~~~~~
460 For a function whose docstring contains examples, DocTestFinder.find()
461 will return a single test (for that function's docstring):
462
463 >>> finder = doctest.DocTestFinder()
464
465 We'll simulate a __file__ attr that ends in pyc:
466
467 >>> from test.test_doctest import test_doctest
468 >>> old = test_doctest.__file__
469 >>> test_doctest.__file__ = 'test_doctest.pyc'
470
471 >>> tests = finder.find(sample_func)
472
473 >>> print(tests) # doctest: +ELLIPSIS
474 [<DocTest sample_func from test_doctest.py:38 (1 example)>]
475
476 The exact name depends on how test_doctest was invoked, so allow for
477 leading path components.
478
479 >>> tests[0].filename # doctest: +ELLIPSIS
480 '...test_doctest.py'
481
482 >>> test_doctest.__file__ = old
483
484
485 >>> e = tests[0].examples[0]
486 >>> (e.source, e.want, e.lineno)
487 ('print(sample_func(22))\n', '44\n', 3)
488
489 By default, tests are created for objects with no docstring:
490
491 >>> def no_docstring(v):
492 ... pass
493 >>> finder.find(no_docstring)
494 []
495
496 However, the optional argument `exclude_empty` to the DocTestFinder
497 constructor can be used to exclude tests for objects with empty
498 docstrings:
499
500 >>> def no_docstring(v):
501 ... pass
502 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
503 >>> excl_empty_finder.find(no_docstring)
504 []
505
506 If the function has a docstring with no examples, then a test with no
507 examples is returned. (This lets `DocTestRunner` collect statistics
508 about which functions have no tests -- but is that useful? And should
509 an empty test also be created when there's no docstring?)
510
511 >>> def no_examples(v):
512 ... ''' no doctest examples '''
513 >>> finder.find(no_examples) # doctest: +ELLIPSIS
514 [<DocTest no_examples from ...:1 (no examples)>]
515
516 Finding Tests in Classes
517 ~~~~~~~~~~~~~~~~~~~~~~~~
518 For a class, DocTestFinder will create a test for the class's
519 docstring, and will recursively explore its contents, including
520 methods, classmethods, staticmethods, properties, and nested classes.
521
522 >>> finder = doctest.DocTestFinder()
523 >>> tests = finder.find(SampleClass)
524 >>> for t in tests:
525 ... print('%2s %s' % (len(t.examples), t.name))
526 3 SampleClass
527 3 SampleClass.NestedClass
528 1 SampleClass.NestedClass.__init__
529 1 SampleClass.__init__
530 1 SampleClass.a_cached_property
531 2 SampleClass.a_classmethod
532 1 SampleClass.a_property
533 1 SampleClass.a_staticmethod
534 1 SampleClass.double
535 1 SampleClass.get
536 3 SampleClass.setter
537
538 New-style classes are also supported:
539
540 >>> tests = finder.find(SampleNewStyleClass)
541 >>> for t in tests:
542 ... print('%2s %s' % (len(t.examples), t.name))
543 1 SampleNewStyleClass
544 1 SampleNewStyleClass.__init__
545 1 SampleNewStyleClass.double
546 1 SampleNewStyleClass.get
547
548 Finding Tests in Modules
549 ~~~~~~~~~~~~~~~~~~~~~~~~
550 For a module, DocTestFinder will create a test for the class's
551 docstring, and will recursively explore its contents, including
552 functions, classes, and the `__test__` dictionary, if it exists:
553
554 >>> # A module
555 >>> import types
556 >>> m = types.ModuleType('some_module')
557 >>> def triple(val):
558 ... '''
559 ... >>> print(triple(11))
560 ... 33
561 ... '''
562 ... return val*3
563 >>> m.__dict__.update({
564 ... 'sample_func': sample_func,
565 ... 'SampleClass': SampleClass,
566 ... '__doc__': '''
567 ... Module docstring.
568 ... >>> print('module')
569 ... module
570 ... ''',
571 ... '__test__': {
572 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
573 ... 'c': triple}})
574
575 >>> finder = doctest.DocTestFinder()
576 >>> # Use module=test_doctest, to prevent doctest from
577 >>> # ignoring the objects since they weren't defined in m.
578 >>> from test.test_doctest import test_doctest
579 >>> tests = finder.find(m, module=test_doctest)
580 >>> for t in tests:
581 ... print('%2s %s' % (len(t.examples), t.name))
582 1 some_module
583 3 some_module.SampleClass
584 3 some_module.SampleClass.NestedClass
585 1 some_module.SampleClass.NestedClass.__init__
586 1 some_module.SampleClass.__init__
587 1 some_module.SampleClass.a_cached_property
588 2 some_module.SampleClass.a_classmethod
589 1 some_module.SampleClass.a_property
590 1 some_module.SampleClass.a_staticmethod
591 1 some_module.SampleClass.double
592 1 some_module.SampleClass.get
593 3 some_module.SampleClass.setter
594 1 some_module.__test__.c
595 2 some_module.__test__.d
596 1 some_module.sample_func
597
598 However, doctest will ignore imported objects from other modules
599 (without proper `module=`):
600
601 >>> import types
602 >>> m = types.ModuleType('poluted_namespace')
603 >>> m.__dict__.update({
604 ... 'sample_func': sample_func,
605 ... 'SampleClass': SampleClass,
606 ... })
607
608 >>> finder = doctest.DocTestFinder()
609 >>> finder.find(m)
610 []
611
612 Duplicate Removal
613 ~~~~~~~~~~~~~~~~~
614 If a single object is listed twice (under different names), then tests
615 will only be generated for it once:
616
617 >>> from test.test_doctest import doctest_aliases
618 >>> assert doctest_aliases.TwoNames.f
619 >>> assert doctest_aliases.TwoNames.g
620 >>> tests = excl_empty_finder.find(doctest_aliases)
621 >>> print(len(tests))
622 2
623 >>> print(tests[0].name)
624 test.test_doctest.doctest_aliases.TwoNames
625
626 TwoNames.f and TwoNames.g are bound to the same object.
627 We can't guess which will be found in doctest's traversal of
628 TwoNames.__dict__ first, so we have to allow for either.
629
630 >>> tests[1].name.split('.')[-1] in ['f', 'g']
631 True
632
633 Empty Tests
634 ~~~~~~~~~~~
635 By default, an object with no doctests doesn't create any tests:
636
637 >>> tests = doctest.DocTestFinder().find(SampleClass)
638 >>> for t in tests:
639 ... print('%2s %s' % (len(t.examples), t.name))
640 3 SampleClass
641 3 SampleClass.NestedClass
642 1 SampleClass.NestedClass.__init__
643 1 SampleClass.__init__
644 1 SampleClass.a_cached_property
645 2 SampleClass.a_classmethod
646 1 SampleClass.a_property
647 1 SampleClass.a_staticmethod
648 1 SampleClass.double
649 1 SampleClass.get
650 3 SampleClass.setter
651
652 By default, that excluded objects with no doctests. exclude_empty=False
653 tells it to include (empty) tests for objects with no doctests. This feature
654 is really to support backward compatibility in what doctest.master.summarize()
655 displays.
656
657 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
658 >>> for t in tests:
659 ... print('%2s %s' % (len(t.examples), t.name))
660 3 SampleClass
661 3 SampleClass.NestedClass
662 1 SampleClass.NestedClass.__init__
663 0 SampleClass.NestedClass.get
664 0 SampleClass.NestedClass.square
665 1 SampleClass.__init__
666 1 SampleClass.a_cached_property
667 2 SampleClass.a_classmethod
668 1 SampleClass.a_property
669 1 SampleClass.a_staticmethod
670 1 SampleClass.double
671 1 SampleClass.get
672 3 SampleClass.setter
673
674 When used with `exclude_empty=False` we are also interested in line numbers
675 of doctests that are empty.
676 It used to be broken for quite some time until `bpo-28249`.
677
678 >>> from test.test_doctest import doctest_lineno
679 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(doctest_lineno)
680 >>> for t in tests:
681 ... print('%5s %s' % (t.lineno, t.name))
682 None test.test_doctest.doctest_lineno
683 None test.test_doctest.doctest_lineno.ClassWithACachedProperty
684 102 test.test_doctest.doctest_lineno.ClassWithACachedProperty.cached
685 22 test.test_doctest.doctest_lineno.ClassWithDocstring
686 30 test.test_doctest.doctest_lineno.ClassWithDoctest
687 None test.test_doctest.doctest_lineno.ClassWithoutDocstring
688 None test.test_doctest.doctest_lineno.MethodWrapper
689 53 test.test_doctest.doctest_lineno.MethodWrapper.classmethod_with_doctest
690 39 test.test_doctest.doctest_lineno.MethodWrapper.method_with_docstring
691 45 test.test_doctest.doctest_lineno.MethodWrapper.method_with_doctest
692 None test.test_doctest.doctest_lineno.MethodWrapper.method_without_docstring
693 61 test.test_doctest.doctest_lineno.MethodWrapper.property_with_doctest
694 86 test.test_doctest.doctest_lineno.cached_func_with_doctest
695 None test.test_doctest.doctest_lineno.cached_func_without_docstring
696 4 test.test_doctest.doctest_lineno.func_with_docstring
697 77 test.test_doctest.doctest_lineno.func_with_docstring_wrapped
698 12 test.test_doctest.doctest_lineno.func_with_doctest
699 None test.test_doctest.doctest_lineno.func_without_docstring
700
701 Turning off Recursion
702 ~~~~~~~~~~~~~~~~~~~~~
703 DocTestFinder can be told not to look for tests in contained objects
704 using the `recurse` flag:
705
706 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
707 >>> for t in tests:
708 ... print('%2s %s' % (len(t.examples), t.name))
709 3 SampleClass
710
711 Line numbers
712 ~~~~~~~~~~~~
713 DocTestFinder finds the line number of each example:
714
715 >>> def f(x):
716 ... '''
717 ... >>> x = 12
718 ...
719 ... some text
720 ...
721 ... >>> # examples are not created for comments & bare prompts.
722 ... >>>
723 ... ...
724 ...
725 ... >>> for x in range(10):
726 ... ... print(x, end=' ')
727 ... 0 1 2 3 4 5 6 7 8 9
728 ... >>> x//2
729 ... 6
730 ... '''
731 >>> test = doctest.DocTestFinder().find(f)[0]
732 >>> [e.lineno for e in test.examples]
733 [1, 9, 12]
734 """
735
736 if int.__doc__: # simple check for --without-doc-strings, skip if lacking
737 def non_Python_modules(): r"""
738
739 Finding Doctests in Modules Not Written in Python
740 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
741 DocTestFinder can also find doctests in most modules not written in Python.
742 We'll use builtins as an example, since it almost certainly isn't written in
743 plain ol' Python and is guaranteed to be available.
744
745 >>> import builtins
746 >>> tests = doctest.DocTestFinder().find(builtins)
747 >>> 830 < len(tests) < 860 # approximate number of objects with docstrings
748 True
749 >>> real_tests = [t for t in tests if len(t.examples) > 0]
750 >>> len(real_tests) # objects that actually have doctests
751 14
752 >>> for t in real_tests:
753 ... print('{} {}'.format(len(t.examples), t.name))
754 ...
755 1 builtins.bin
756 5 builtins.bytearray.hex
757 5 builtins.bytes.hex
758 3 builtins.float.as_integer_ratio
759 2 builtins.float.fromhex
760 2 builtins.float.hex
761 1 builtins.hex
762 1 builtins.int
763 3 builtins.int.as_integer_ratio
764 2 builtins.int.bit_count
765 2 builtins.int.bit_length
766 5 builtins.memoryview.hex
767 1 builtins.oct
768 1 builtins.zip
769
770 Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
771 'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
772 and 'int' is a type.
773 """
774
775
776 class TestDocTest(unittest.TestCase):
777
778 def test_run(self):
779 test = '''
780 >>> 1 + 1
781 11
782 >>> 2 + 3 # doctest: +SKIP
783 "23"
784 >>> 5 + 7
785 57
786 '''
787
788 def myfunc():
789 pass
790 myfunc.__doc__ = test
791
792 # test DocTestFinder.run()
793 test = doctest.DocTestFinder().find(myfunc)[0]
794 with support.captured_stdout():
795 with support.captured_stderr():
796 results = doctest.DocTestRunner(verbose=False).run(test)
797
798 # test TestResults
799 self.assertIsInstance(results, doctest.TestResults)
800 self.assertEqual(results.failed, 2)
801 self.assertEqual(results.attempted, 3)
802 self.assertEqual(results.skipped, 1)
803 self.assertEqual(tuple(results), (2, 3))
804 x, y = results
805 self.assertEqual((x, y), (2, 3))
806
807
808 class TestDocTestFinder(unittest.TestCase):
809
810 def test_issue35753(self):
811 # This import of `call` should trigger issue35753 when
812 # DocTestFinder.find() is called due to inspect.unwrap() failing,
813 # however with a patched doctest this should succeed.
814 from unittest.mock import call
815 dummy_module = types.ModuleType("dummy")
816 dummy_module.__dict__['inject_call'] = call
817 finder = doctest.DocTestFinder()
818 self.assertEqual(finder.find(dummy_module), [])
819
820 def test_empty_namespace_package(self):
821 pkg_name = 'doctest_empty_pkg'
822 with tempfile.TemporaryDirectory() as parent_dir:
823 pkg_dir = os.path.join(parent_dir, pkg_name)
824 os.mkdir(pkg_dir)
825 sys.path.append(parent_dir)
826 try:
827 mod = importlib.import_module(pkg_name)
828 finally:
829 import_helper.forget(pkg_name)
830 sys.path.pop()
831
832 include_empty_finder = doctest.DocTestFinder(exclude_empty=False)
833 exclude_empty_finder = doctest.DocTestFinder(exclude_empty=True)
834
835 self.assertEqual(len(include_empty_finder.find(mod)), 1)
836 self.assertEqual(len(exclude_empty_finder.find(mod)), 0)
837
838 def test_DocTestParser(): r"""
839 Unit tests for the `DocTestParser` class.
840
841 DocTestParser is used to parse docstrings containing doctest examples.
842
843 The `parse` method divides a docstring into examples and intervening
844 text:
845
846 >>> s = '''
847 ... >>> x, y = 2, 3 # no output expected
848 ... >>> if 1:
849 ... ... print(x)
850 ... ... print(y)
851 ... 2
852 ... 3
853 ...
854 ... Some text.
855 ... >>> x+y
856 ... 5
857 ... '''
858 >>> parser = doctest.DocTestParser()
859 >>> for piece in parser.parse(s):
860 ... if isinstance(piece, doctest.Example):
861 ... print('Example:', (piece.source, piece.want, piece.lineno))
862 ... else:
863 ... print(' Text:', repr(piece))
864 Text: '\n'
865 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
866 Text: ''
867 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
868 Text: '\nSome text.\n'
869 Example: ('x+y\n', '5\n', 9)
870 Text: ''
871
872 The `get_examples` method returns just the examples:
873
874 >>> for piece in parser.get_examples(s):
875 ... print((piece.source, piece.want, piece.lineno))
876 ('x, y = 2, 3 # no output expected\n', '', 1)
877 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
878 ('x+y\n', '5\n', 9)
879
880 The `get_doctest` method creates a Test from the examples, along with the
881 given arguments:
882
883 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
884 >>> (test.name, test.filename, test.lineno)
885 ('name', 'filename', 5)
886 >>> for piece in test.examples:
887 ... print((piece.source, piece.want, piece.lineno))
888 ('x, y = 2, 3 # no output expected\n', '', 1)
889 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
890 ('x+y\n', '5\n', 9)
891 """
892
893 class test_DocTestRunner:
894 def basics(): r"""
895 Unit tests for the `DocTestRunner` class.
896
897 DocTestRunner is used to run DocTest test cases, and to accumulate
898 statistics. Here's a simple DocTest case we can use:
899
900 >>> save_colorize = _colorize.COLORIZE
901 >>> _colorize.COLORIZE = False
902
903 >>> def f(x):
904 ... '''
905 ... >>> x = 12
906 ... >>> print(x)
907 ... 12
908 ... >>> x//2
909 ... 6
910 ... '''
911 >>> test = doctest.DocTestFinder().find(f)[0]
912
913 The main DocTestRunner interface is the `run` method, which runs a
914 given DocTest case in a given namespace (globs). It returns a tuple
915 `(f,t)`, where `f` is the number of failed tests and `t` is the number
916 of tried tests.
917
918 >>> doctest.DocTestRunner(verbose=False).run(test)
919 TestResults(failed=0, attempted=3)
920
921 If any example produces incorrect output, then the test runner reports
922 the failure and proceeds to the next example:
923
924 >>> def f(x):
925 ... '''
926 ... >>> x = 12
927 ... >>> print(x)
928 ... 14
929 ... >>> x//2
930 ... 6
931 ... '''
932 >>> test = doctest.DocTestFinder().find(f)[0]
933 >>> doctest.DocTestRunner(verbose=True).run(test)
934 ... # doctest: +ELLIPSIS
935 Trying:
936 x = 12
937 Expecting nothing
938 ok
939 Trying:
940 print(x)
941 Expecting:
942 14
943 **********************************************************************
944 File ..., line 4, in f
945 Failed example:
946 print(x)
947 Expected:
948 14
949 Got:
950 12
951 Trying:
952 x//2
953 Expecting:
954 6
955 ok
956 TestResults(failed=1, attempted=3)
957
958 >>> _colorize.COLORIZE = save_colorize
959 """
960 def verbose_flag(): r"""
961 The `verbose` flag makes the test runner generate more detailed
962 output:
963
964 >>> def f(x):
965 ... '''
966 ... >>> x = 12
967 ... >>> print(x)
968 ... 12
969 ... >>> x//2
970 ... 6
971 ... '''
972 >>> test = doctest.DocTestFinder().find(f)[0]
973
974 >>> doctest.DocTestRunner(verbose=True).run(test)
975 Trying:
976 x = 12
977 Expecting nothing
978 ok
979 Trying:
980 print(x)
981 Expecting:
982 12
983 ok
984 Trying:
985 x//2
986 Expecting:
987 6
988 ok
989 TestResults(failed=0, attempted=3)
990
991 If the `verbose` flag is unspecified, then the output will be verbose
992 iff `-v` appears in sys.argv:
993
994 >>> # Save the real sys.argv list.
995 >>> old_argv = sys.argv
996
997 >>> # If -v does not appear in sys.argv, then output isn't verbose.
998 >>> sys.argv = ['test']
999 >>> doctest.DocTestRunner().run(test)
1000 TestResults(failed=0, attempted=3)
1001
1002 >>> # If -v does appear in sys.argv, then output is verbose.
1003 >>> sys.argv = ['test', '-v']
1004 >>> doctest.DocTestRunner().run(test)
1005 Trying:
1006 x = 12
1007 Expecting nothing
1008 ok
1009 Trying:
1010 print(x)
1011 Expecting:
1012 12
1013 ok
1014 Trying:
1015 x//2
1016 Expecting:
1017 6
1018 ok
1019 TestResults(failed=0, attempted=3)
1020
1021 >>> # Restore sys.argv
1022 >>> sys.argv = old_argv
1023
1024 In the remaining examples, the test runner's verbosity will be
1025 explicitly set, to ensure that the test behavior is consistent.
1026 """
1027 def exceptions(): r"""
1028 Tests of `DocTestRunner`'s exception handling.
1029
1030 An expected exception is specified with a traceback message. The
1031 lines between the first line and the type/value may be omitted or
1032 replaced with any other string:
1033
1034 >>> save_colorize = _colorize.COLORIZE
1035 >>> _colorize.COLORIZE = False
1036
1037 >>> def f(x):
1038 ... '''
1039 ... >>> x = 12
1040 ... >>> print(x//0)
1041 ... Traceback (most recent call last):
1042 ... ZeroDivisionError: integer division or modulo by zero
1043 ... '''
1044 >>> test = doctest.DocTestFinder().find(f)[0]
1045 >>> doctest.DocTestRunner(verbose=False).run(test)
1046 TestResults(failed=0, attempted=2)
1047
1048 An example may not generate output before it raises an exception; if
1049 it does, then the traceback message will not be recognized as
1050 signaling an expected exception, so the example will be reported as an
1051 unexpected exception:
1052
1053 >>> def f(x):
1054 ... '''
1055 ... >>> x = 12
1056 ... >>> print('pre-exception output', x//0)
1057 ... pre-exception output
1058 ... Traceback (most recent call last):
1059 ... ZeroDivisionError: integer division or modulo by zero
1060 ... '''
1061 >>> test = doctest.DocTestFinder().find(f)[0]
1062 >>> doctest.DocTestRunner(verbose=False).run(test)
1063 ... # doctest: +ELLIPSIS
1064 **********************************************************************
1065 File ..., line 4, in f
1066 Failed example:
1067 print('pre-exception output', x//0)
1068 Exception raised:
1069 ...
1070 ZeroDivisionError: integer division or modulo by zero
1071 TestResults(failed=1, attempted=2)
1072
1073 Exception messages may contain newlines:
1074
1075 >>> def f(x):
1076 ... r'''
1077 ... >>> raise ValueError('multi\nline\nmessage')
1078 ... Traceback (most recent call last):
1079 ... ValueError: multi
1080 ... line
1081 ... message
1082 ... '''
1083 >>> test = doctest.DocTestFinder().find(f)[0]
1084 >>> doctest.DocTestRunner(verbose=False).run(test)
1085 TestResults(failed=0, attempted=1)
1086
1087 If an exception is expected, but an exception with the wrong type or
1088 message is raised, then it is reported as a failure:
1089
1090 >>> def f(x):
1091 ... r'''
1092 ... >>> raise ValueError('message')
1093 ... Traceback (most recent call last):
1094 ... ValueError: wrong message
1095 ... '''
1096 >>> test = doctest.DocTestFinder().find(f)[0]
1097 >>> doctest.DocTestRunner(verbose=False).run(test)
1098 ... # doctest: +ELLIPSIS
1099 **********************************************************************
1100 File ..., line 3, in f
1101 Failed example:
1102 raise ValueError('message')
1103 Expected:
1104 Traceback (most recent call last):
1105 ValueError: wrong message
1106 Got:
1107 Traceback (most recent call last):
1108 ...
1109 ValueError: message
1110 TestResults(failed=1, attempted=1)
1111
1112 However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
1113 detail:
1114
1115 >>> def f(x):
1116 ... r'''
1117 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1118 ... Traceback (most recent call last):
1119 ... ValueError: wrong message
1120 ... '''
1121 >>> test = doctest.DocTestFinder().find(f)[0]
1122 >>> doctest.DocTestRunner(verbose=False).run(test)
1123 TestResults(failed=0, attempted=1)
1124
1125 IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
1126 between Python versions. For example, in Python 2.x, the module path of
1127 the exception is not in the output, but this will fail under Python 3:
1128
1129 >>> def f(x):
1130 ... r'''
1131 ... >>> from http.client import HTTPException
1132 ... >>> raise HTTPException('message')
1133 ... Traceback (most recent call last):
1134 ... HTTPException: message
1135 ... '''
1136 >>> test = doctest.DocTestFinder().find(f)[0]
1137 >>> doctest.DocTestRunner(verbose=False).run(test)
1138 ... # doctest: +ELLIPSIS
1139 **********************************************************************
1140 File ..., line 4, in f
1141 Failed example:
1142 raise HTTPException('message')
1143 Expected:
1144 Traceback (most recent call last):
1145 HTTPException: message
1146 Got:
1147 Traceback (most recent call last):
1148 ...
1149 http.client.HTTPException: message
1150 TestResults(failed=1, attempted=2)
1151
1152 But in Python 3 the module path is included, and therefore a test must look
1153 like the following test to succeed in Python 3. But that test will fail under
1154 Python 2.
1155
1156 >>> def f(x):
1157 ... r'''
1158 ... >>> from http.client import HTTPException
1159 ... >>> raise HTTPException('message')
1160 ... Traceback (most recent call last):
1161 ... http.client.HTTPException: message
1162 ... '''
1163 >>> test = doctest.DocTestFinder().find(f)[0]
1164 >>> doctest.DocTestRunner(verbose=False).run(test)
1165 TestResults(failed=0, attempted=2)
1166
1167 However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
1168 (or its unexpected absence) will be ignored:
1169
1170 >>> def f(x):
1171 ... r'''
1172 ... >>> from http.client import HTTPException
1173 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1174 ... Traceback (most recent call last):
1175 ... HTTPException: message
1176 ... '''
1177 >>> test = doctest.DocTestFinder().find(f)[0]
1178 >>> doctest.DocTestRunner(verbose=False).run(test)
1179 TestResults(failed=0, attempted=2)
1180
1181 The module path will be completely ignored, so two different module paths will
1182 still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
1183 be used when exceptions have changed module.
1184
1185 >>> def f(x):
1186 ... r'''
1187 ... >>> from http.client import HTTPException
1188 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1189 ... Traceback (most recent call last):
1190 ... foo.bar.HTTPException: message
1191 ... '''
1192 >>> test = doctest.DocTestFinder().find(f)[0]
1193 >>> doctest.DocTestRunner(verbose=False).run(test)
1194 TestResults(failed=0, attempted=2)
1195
1196 But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1197
1198 >>> def f(x):
1199 ... r'''
1200 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1201 ... Traceback (most recent call last):
1202 ... TypeError: wrong type
1203 ... '''
1204 >>> test = doctest.DocTestFinder().find(f)[0]
1205 >>> doctest.DocTestRunner(verbose=False).run(test)
1206 ... # doctest: +ELLIPSIS
1207 **********************************************************************
1208 File ..., line 3, in f
1209 Failed example:
1210 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
1211 Expected:
1212 Traceback (most recent call last):
1213 TypeError: wrong type
1214 Got:
1215 Traceback (most recent call last):
1216 ...
1217 ValueError: message
1218 TestResults(failed=1, attempted=1)
1219
1220 If the exception does not have a message, you can still use
1221 IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
1222
1223 >>> def f(x):
1224 ... r'''
1225 ... >>> from http.client import HTTPException
1226 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1227 ... Traceback (most recent call last):
1228 ... foo.bar.HTTPException
1229 ... '''
1230 >>> test = doctest.DocTestFinder().find(f)[0]
1231 >>> doctest.DocTestRunner(verbose=False).run(test)
1232 TestResults(failed=0, attempted=2)
1233
1234 Note that a trailing colon doesn't matter either:
1235
1236 >>> def f(x):
1237 ... r'''
1238 ... >>> from http.client import HTTPException
1239 ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
1240 ... Traceback (most recent call last):
1241 ... foo.bar.HTTPException:
1242 ... '''
1243 >>> test = doctest.DocTestFinder().find(f)[0]
1244 >>> doctest.DocTestRunner(verbose=False).run(test)
1245 TestResults(failed=0, attempted=2)
1246
1247 If an exception is raised but not expected, then it is reported as an
1248 unexpected exception:
1249
1250 >>> def f(x):
1251 ... r'''
1252 ... >>> 1//0
1253 ... 0
1254 ... '''
1255 >>> test = doctest.DocTestFinder().find(f)[0]
1256 >>> doctest.DocTestRunner(verbose=False).run(test)
1257 ... # doctest: +ELLIPSIS
1258 **********************************************************************
1259 File ..., line 3, in f
1260 Failed example:
1261 1//0
1262 Exception raised:
1263 Traceback (most recent call last):
1264 ...
1265 ZeroDivisionError: integer division or modulo by zero
1266 TestResults(failed=1, attempted=1)
1267
1268 >>> _colorize.COLORIZE = save_colorize
1269 """
1270 def displayhook(): r"""
1271 Test that changing sys.displayhook doesn't matter for doctest.
1272
1273 >>> import sys
1274 >>> orig_displayhook = sys.displayhook
1275 >>> def my_displayhook(x):
1276 ... print('hi!')
1277 >>> sys.displayhook = my_displayhook
1278 >>> def f():
1279 ... '''
1280 ... >>> 3
1281 ... 3
1282 ... '''
1283 >>> test = doctest.DocTestFinder().find(f)[0]
1284 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1285 >>> post_displayhook = sys.displayhook
1286
1287 We need to restore sys.displayhook now, so that we'll be able to test
1288 results.
1289
1290 >>> sys.displayhook = orig_displayhook
1291
1292 Ok, now we can check that everything is ok.
1293
1294 >>> r
1295 TestResults(failed=0, attempted=1)
1296 >>> post_displayhook is my_displayhook
1297 True
1298 """
1299 def optionflags(): r"""
1300 Tests of `DocTestRunner`'s option flag handling.
1301
1302 Several option flags can be used to customize the behavior of the test
1303 runner. These are defined as module constants in doctest, and passed
1304 to the DocTestRunner constructor (multiple constants should be ORed
1305 together).
1306
1307 The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1308 and 1/0:
1309
1310 >>> save_colorize = _colorize.COLORIZE
1311 >>> _colorize.COLORIZE = False
1312
1313 >>> def f(x):
1314 ... '>>> True\n1\n'
1315
1316 >>> # Without the flag:
1317 >>> test = doctest.DocTestFinder().find(f)[0]
1318 >>> doctest.DocTestRunner(verbose=False).run(test)
1319 TestResults(failed=0, attempted=1)
1320
1321 >>> # With the flag:
1322 >>> test = doctest.DocTestFinder().find(f)[0]
1323 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1324 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1325 ... # doctest: +ELLIPSIS
1326 **********************************************************************
1327 File ..., line 2, in f
1328 Failed example:
1329 True
1330 Expected:
1331 1
1332 Got:
1333 True
1334 TestResults(failed=1, attempted=1)
1335
1336 The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1337 and the '<BLANKLINE>' marker:
1338
1339 >>> def f(x):
1340 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
1341
1342 >>> # Without the flag:
1343 >>> test = doctest.DocTestFinder().find(f)[0]
1344 >>> doctest.DocTestRunner(verbose=False).run(test)
1345 TestResults(failed=0, attempted=1)
1346
1347 >>> # With the flag:
1348 >>> test = doctest.DocTestFinder().find(f)[0]
1349 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1350 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1351 ... # doctest: +ELLIPSIS
1352 **********************************************************************
1353 File ..., line 2, in f
1354 Failed example:
1355 print("a\n\nb")
1356 Expected:
1357 a
1358 <BLANKLINE>
1359 b
1360 Got:
1361 a
1362 <BLANKLINE>
1363 b
1364 TestResults(failed=1, attempted=1)
1365
1366 The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1367 treated as equal:
1368
1369 >>> def f(x):
1370 ... '\n>>> print(1, 2, 3)\n 1 2\n 3'
1371
1372 >>> # Without the flag:
1373 >>> test = doctest.DocTestFinder().find(f)[0]
1374 >>> doctest.DocTestRunner(verbose=False).run(test)
1375 ... # doctest: +ELLIPSIS
1376 **********************************************************************
1377 File ..., line 3, in f
1378 Failed example:
1379 print(1, 2, 3)
1380 Expected:
1381 1 2
1382 3
1383 Got:
1384 1 2 3
1385 TestResults(failed=1, attempted=1)
1386
1387 >>> # With the flag:
1388 >>> test = doctest.DocTestFinder().find(f)[0]
1389 >>> flags = doctest.NORMALIZE_WHITESPACE
1390 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1391 TestResults(failed=0, attempted=1)
1392
1393 An example from the docs:
1394 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
1395 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1396 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1397
1398 The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1399 output to match any substring in the actual output:
1400
1401 >>> def f(x):
1402 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
1403
1404 >>> # Without the flag:
1405 >>> test = doctest.DocTestFinder().find(f)[0]
1406 >>> doctest.DocTestRunner(verbose=False).run(test)
1407 ... # doctest: +ELLIPSIS
1408 **********************************************************************
1409 File ..., line 2, in f
1410 Failed example:
1411 print(list(range(15)))
1412 Expected:
1413 [0, 1, 2, ..., 14]
1414 Got:
1415 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
1416 TestResults(failed=1, attempted=1)
1417
1418 >>> # With the flag:
1419 >>> test = doctest.DocTestFinder().find(f)[0]
1420 >>> flags = doctest.ELLIPSIS
1421 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1422 TestResults(failed=0, attempted=1)
1423
1424 ... also matches nothing:
1425
1426 >>> if 1:
1427 ... for i in range(100):
1428 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1429 ... print('!')
1430 0 1...4...9 16 ... 36 49 64 ... 9801 !
1431
1432 ... can be surprising; e.g., this test passes:
1433
1434 >>> if 1: #doctest: +ELLIPSIS
1435 ... for i in range(20):
1436 ... print(i, end=' ')
1437 ... print(20)
1438 0 1 2 ...1...2...0
1439
1440 Examples from the docs:
1441
1442 >>> print(list(range(20))) # doctest:+ELLIPSIS
1443 [0, 1, ..., 18, 19]
1444
1445 >>> print(list(range(20))) # doctest: +ELLIPSIS
1446 ... # doctest: +NORMALIZE_WHITESPACE
1447 [0, 1, ..., 18, 19]
1448
1449 The SKIP flag causes an example to be skipped entirely. I.e., the
1450 example is not run. It can be useful in contexts where doctest
1451 examples serve as both documentation and test cases, and an example
1452 should be included for documentation purposes, but should not be
1453 checked (e.g., because its output is random, or depends on resources
1454 which would be unavailable.) The SKIP flag can also be used for
1455 'commenting out' broken examples.
1456
1457 >>> import unavailable_resource # doctest: +SKIP
1458 >>> unavailable_resource.do_something() # doctest: +SKIP
1459 >>> unavailable_resource.blow_up() # doctest: +SKIP
1460 Traceback (most recent call last):
1461 ...
1462 UncheckedBlowUpError: Nobody checks me.
1463
1464 >>> import random
1465 >>> print(random.random()) # doctest: +SKIP
1466 0.721216923889
1467
1468 The REPORT_UDIFF flag causes failures that involve multi-line expected
1469 and actual outputs to be displayed using a unified diff:
1470
1471 >>> def f(x):
1472 ... r'''
1473 ... >>> print('\n'.join('abcdefg'))
1474 ... a
1475 ... B
1476 ... c
1477 ... d
1478 ... f
1479 ... g
1480 ... h
1481 ... '''
1482
1483 >>> # Without the flag:
1484 >>> test = doctest.DocTestFinder().find(f)[0]
1485 >>> doctest.DocTestRunner(verbose=False).run(test)
1486 ... # doctest: +ELLIPSIS
1487 **********************************************************************
1488 File ..., line 3, in f
1489 Failed example:
1490 print('\n'.join('abcdefg'))
1491 Expected:
1492 a
1493 B
1494 c
1495 d
1496 f
1497 g
1498 h
1499 Got:
1500 a
1501 b
1502 c
1503 d
1504 e
1505 f
1506 g
1507 TestResults(failed=1, attempted=1)
1508
1509 >>> # With the flag:
1510 >>> test = doctest.DocTestFinder().find(f)[0]
1511 >>> flags = doctest.REPORT_UDIFF
1512 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1513 ... # doctest: +ELLIPSIS
1514 **********************************************************************
1515 File ..., line 3, in f
1516 Failed example:
1517 print('\n'.join('abcdefg'))
1518 Differences (unified diff with -expected +actual):
1519 @@ -1,7 +1,7 @@
1520 a
1521 -B
1522 +b
1523 c
1524 d
1525 +e
1526 f
1527 g
1528 -h
1529 TestResults(failed=1, attempted=1)
1530
1531 The REPORT_CDIFF flag causes failures that involve multi-line expected
1532 and actual outputs to be displayed using a context diff:
1533
1534 >>> # Reuse f() from the REPORT_UDIFF example, above.
1535 >>> test = doctest.DocTestFinder().find(f)[0]
1536 >>> flags = doctest.REPORT_CDIFF
1537 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1538 ... # doctest: +ELLIPSIS
1539 **********************************************************************
1540 File ..., line 3, in f
1541 Failed example:
1542 print('\n'.join('abcdefg'))
1543 Differences (context diff with expected followed by actual):
1544 ***************
1545 *** 1,7 ****
1546 a
1547 ! B
1548 c
1549 d
1550 f
1551 g
1552 - h
1553 --- 1,7 ----
1554 a
1555 ! b
1556 c
1557 d
1558 + e
1559 f
1560 g
1561 TestResults(failed=1, attempted=1)
1562
1563
1564 The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
1565 used by the popular ndiff.py utility. This does intraline difference
1566 marking, as well as interline differences.
1567
1568 >>> def f(x):
1569 ... r'''
1570 ... >>> print("a b c d e f g h i j k l m")
1571 ... a b c d e f g h i j k 1 m
1572 ... '''
1573 >>> test = doctest.DocTestFinder().find(f)[0]
1574 >>> flags = doctest.REPORT_NDIFF
1575 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1576 ... # doctest: +ELLIPSIS
1577 **********************************************************************
1578 File ..., line 3, in f
1579 Failed example:
1580 print("a b c d e f g h i j k l m")
1581 Differences (ndiff with -expected +actual):
1582 - a b c d e f g h i j k 1 m
1583 ? ^
1584 + a b c d e f g h i j k l m
1585 ? + ++ ^
1586 TestResults(failed=1, attempted=1)
1587
1588 The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
1589 failing example:
1590
1591 >>> def f(x):
1592 ... r'''
1593 ... >>> print(1) # first success
1594 ... 1
1595 ... >>> print(2) # first failure
1596 ... 200
1597 ... >>> print(3) # second failure
1598 ... 300
1599 ... >>> print(4) # second success
1600 ... 4
1601 ... >>> print(5) # third failure
1602 ... 500
1603 ... '''
1604 >>> test = doctest.DocTestFinder().find(f)[0]
1605 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1606 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1607 ... # doctest: +ELLIPSIS
1608 **********************************************************************
1609 File ..., line 5, in f
1610 Failed example:
1611 print(2) # first failure
1612 Expected:
1613 200
1614 Got:
1615 2
1616 TestResults(failed=3, attempted=5)
1617
1618 However, output from `report_start` is not suppressed:
1619
1620 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
1621 ... # doctest: +ELLIPSIS
1622 Trying:
1623 print(1) # first success
1624 Expecting:
1625 1
1626 ok
1627 Trying:
1628 print(2) # first failure
1629 Expecting:
1630 200
1631 **********************************************************************
1632 File ..., line 5, in f
1633 Failed example:
1634 print(2) # first failure
1635 Expected:
1636 200
1637 Got:
1638 2
1639 TestResults(failed=3, attempted=5)
1640
1641 The FAIL_FAST flag causes the runner to exit after the first failing example,
1642 so subsequent examples are not even attempted:
1643
1644 >>> flags = doctest.FAIL_FAST
1645 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1646 ... # doctest: +ELLIPSIS
1647 **********************************************************************
1648 File ..., line 5, in f
1649 Failed example:
1650 print(2) # first failure
1651 Expected:
1652 200
1653 Got:
1654 2
1655 TestResults(failed=1, attempted=2)
1656
1657 Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1658 FAIL_FAST only:
1659
1660 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1661 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1662 ... # doctest: +ELLIPSIS
1663 **********************************************************************
1664 File ..., line 5, in f
1665 Failed example:
1666 print(2) # first failure
1667 Expected:
1668 200
1669 Got:
1670 2
1671 TestResults(failed=1, attempted=2)
1672
1673 For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1674 exceptions count as failures:
1675
1676 >>> def f(x):
1677 ... r'''
1678 ... >>> print(1) # first success
1679 ... 1
1680 ... >>> raise ValueError(2) # first failure
1681 ... 200
1682 ... >>> print(3) # second failure
1683 ... 300
1684 ... >>> print(4) # second success
1685 ... 4
1686 ... >>> print(5) # third failure
1687 ... 500
1688 ... '''
1689 >>> test = doctest.DocTestFinder().find(f)[0]
1690 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1691 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1692 ... # doctest: +ELLIPSIS
1693 **********************************************************************
1694 File ..., line 5, in f
1695 Failed example:
1696 raise ValueError(2) # first failure
1697 Exception raised:
1698 ...
1699 ValueError: 2
1700 TestResults(failed=3, attempted=5)
1701 >>> flags = doctest.FAIL_FAST
1702 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1703 ... # doctest: +ELLIPSIS
1704 **********************************************************************
1705 File ..., line 5, in f
1706 Failed example:
1707 raise ValueError(2) # first failure
1708 Exception raised:
1709 ...
1710 ValueError: 2
1711 TestResults(failed=1, attempted=2)
1712
1713 New option flags can also be registered, via register_optionflag(). Here
1714 we reach into doctest's internals a bit.
1715
1716 >>> unlikely = "UNLIKELY_OPTION_NAME"
1717 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1718 False
1719 >>> new_flag_value = doctest.register_optionflag(unlikely)
1720 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1721 True
1722
1723 Before 2.4.4/2.5, registering a name more than once erroneously created
1724 more than one flag value. Here we verify that's fixed:
1725
1726 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1727 >>> redundant_flag_value == new_flag_value
1728 True
1729
1730 Clean up.
1731 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1732 >>> _colorize.COLORIZE = save_colorize
1733
1734 """
1735
1736 def option_directives(): r"""
1737 Tests of `DocTestRunner`'s option directive mechanism.
1738
1739 Option directives can be used to turn option flags on or off for a
1740 single example. To turn an option on for an example, follow that
1741 example with a comment of the form ``# doctest: +OPTION``:
1742
1743 >>> save_colorize = _colorize.COLORIZE
1744 >>> _colorize.COLORIZE = False
1745
1746 >>> def f(x): r'''
1747 ... >>> print(list(range(10))) # should fail: no ellipsis
1748 ... [0, 1, ..., 9]
1749 ...
1750 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
1751 ... [0, 1, ..., 9]
1752 ... '''
1753 >>> test = doctest.DocTestFinder().find(f)[0]
1754 >>> doctest.DocTestRunner(verbose=False).run(test)
1755 ... # doctest: +ELLIPSIS
1756 **********************************************************************
1757 File ..., line 2, in f
1758 Failed example:
1759 print(list(range(10))) # should fail: no ellipsis
1760 Expected:
1761 [0, 1, ..., 9]
1762 Got:
1763 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1764 TestResults(failed=1, attempted=2)
1765
1766 To turn an option off for an example, follow that example with a
1767 comment of the form ``# doctest: -OPTION``:
1768
1769 >>> def f(x): r'''
1770 ... >>> print(list(range(10)))
1771 ... [0, 1, ..., 9]
1772 ...
1773 ... >>> # should fail: no ellipsis
1774 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
1775 ... [0, 1, ..., 9]
1776 ... '''
1777 >>> test = doctest.DocTestFinder().find(f)[0]
1778 >>> doctest.DocTestRunner(verbose=False,
1779 ... optionflags=doctest.ELLIPSIS).run(test)
1780 ... # doctest: +ELLIPSIS
1781 **********************************************************************
1782 File ..., line 6, in f
1783 Failed example:
1784 print(list(range(10))) # doctest: -ELLIPSIS
1785 Expected:
1786 [0, 1, ..., 9]
1787 Got:
1788 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1789 TestResults(failed=1, attempted=2)
1790
1791 Option directives affect only the example that they appear with; they
1792 do not change the options for surrounding examples:
1793
1794 >>> def f(x): r'''
1795 ... >>> print(list(range(10))) # Should fail: no ellipsis
1796 ... [0, 1, ..., 9]
1797 ...
1798 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
1799 ... [0, 1, ..., 9]
1800 ...
1801 ... >>> print(list(range(10))) # Should fail: no ellipsis
1802 ... [0, 1, ..., 9]
1803 ... '''
1804 >>> test = doctest.DocTestFinder().find(f)[0]
1805 >>> doctest.DocTestRunner(verbose=False).run(test)
1806 ... # doctest: +ELLIPSIS
1807 **********************************************************************
1808 File ..., line 2, in f
1809 Failed example:
1810 print(list(range(10))) # Should fail: no ellipsis
1811 Expected:
1812 [0, 1, ..., 9]
1813 Got:
1814 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1815 **********************************************************************
1816 File ..., line 8, in f
1817 Failed example:
1818 print(list(range(10))) # Should fail: no ellipsis
1819 Expected:
1820 [0, 1, ..., 9]
1821 Got:
1822 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1823 TestResults(failed=2, attempted=3)
1824
1825 Multiple options may be modified by a single option directive. They
1826 may be separated by whitespace, commas, or both:
1827
1828 >>> def f(x): r'''
1829 ... >>> print(list(range(10))) # Should fail
1830 ... [0, 1, ..., 9]
1831 ... >>> print(list(range(10))) # Should succeed
1832 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
1833 ... [0, 1, ..., 9]
1834 ... '''
1835 >>> test = doctest.DocTestFinder().find(f)[0]
1836 >>> doctest.DocTestRunner(verbose=False).run(test)
1837 ... # doctest: +ELLIPSIS
1838 **********************************************************************
1839 File ..., line 2, in f
1840 Failed example:
1841 print(list(range(10))) # Should fail
1842 Expected:
1843 [0, 1, ..., 9]
1844 Got:
1845 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1846 TestResults(failed=1, attempted=2)
1847
1848 >>> def f(x): r'''
1849 ... >>> print(list(range(10))) # Should fail
1850 ... [0, 1, ..., 9]
1851 ... >>> print(list(range(10))) # Should succeed
1852 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1853 ... [0, 1, ..., 9]
1854 ... '''
1855 >>> test = doctest.DocTestFinder().find(f)[0]
1856 >>> doctest.DocTestRunner(verbose=False).run(test)
1857 ... # doctest: +ELLIPSIS
1858 **********************************************************************
1859 File ..., line 2, in f
1860 Failed example:
1861 print(list(range(10))) # Should fail
1862 Expected:
1863 [0, 1, ..., 9]
1864 Got:
1865 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1866 TestResults(failed=1, attempted=2)
1867
1868 >>> def f(x): r'''
1869 ... >>> print(list(range(10))) # Should fail
1870 ... [0, 1, ..., 9]
1871 ... >>> print(list(range(10))) # Should succeed
1872 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1873 ... [0, 1, ..., 9]
1874 ... '''
1875 >>> test = doctest.DocTestFinder().find(f)[0]
1876 >>> doctest.DocTestRunner(verbose=False).run(test)
1877 ... # doctest: +ELLIPSIS
1878 **********************************************************************
1879 File ..., line 2, in f
1880 Failed example:
1881 print(list(range(10))) # Should fail
1882 Expected:
1883 [0, 1, ..., 9]
1884 Got:
1885 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1886 TestResults(failed=1, attempted=2)
1887
1888 The option directive may be put on the line following the source, as
1889 long as a continuation prompt is used:
1890
1891 >>> def f(x): r'''
1892 ... >>> print(list(range(10)))
1893 ... ... # doctest: +ELLIPSIS
1894 ... [0, 1, ..., 9]
1895 ... '''
1896 >>> test = doctest.DocTestFinder().find(f)[0]
1897 >>> doctest.DocTestRunner(verbose=False).run(test)
1898 TestResults(failed=0, attempted=1)
1899
1900 For examples with multi-line source, the option directive may appear
1901 at the end of any line:
1902
1903 >>> def f(x): r'''
1904 ... >>> for x in range(10): # doctest: +ELLIPSIS
1905 ... ... print(' ', x, end='', sep='')
1906 ... 0 1 2 ... 9
1907 ...
1908 ... >>> for x in range(10):
1909 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1910 ... 0 1 2 ... 9
1911 ... '''
1912 >>> test = doctest.DocTestFinder().find(f)[0]
1913 >>> doctest.DocTestRunner(verbose=False).run(test)
1914 TestResults(failed=0, attempted=2)
1915
1916 If more than one line of an example with multi-line source has an
1917 option directive, then they are combined:
1918
1919 >>> def f(x): r'''
1920 ... Should fail (option directive not on the last line):
1921 ... >>> for x in range(10): # doctest: +ELLIPSIS
1922 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
1923 ... 0 1 2...9
1924 ... '''
1925 >>> test = doctest.DocTestFinder().find(f)[0]
1926 >>> doctest.DocTestRunner(verbose=False).run(test)
1927 TestResults(failed=0, attempted=1)
1928
1929 It is an error to have a comment of the form ``# doctest:`` that is
1930 *not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1931 ``OPTION`` is an option that has been registered with
1932 `register_option`:
1933
1934 >>> # Error: Option not registered
1935 >>> s = '>>> print(12) #doctest: +BADOPTION'
1936 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1937 Traceback (most recent call last):
1938 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1939
1940 >>> # Error: No + or - prefix
1941 >>> s = '>>> print(12) #doctest: ELLIPSIS'
1942 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1943 Traceback (most recent call last):
1944 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1945
1946 It is an error to use an option directive on a line that contains no
1947 source:
1948
1949 >>> s = '>>> # doctest: +ELLIPSIS'
1950 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1951 Traceback (most recent call last):
1952 ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
1953
1954 >>> _colorize.COLORIZE = save_colorize
1955 """
1956
1957 def test_testsource(): r"""
1958 Unit tests for `testsource()`.
1959
1960 The testsource() function takes a module and a name, finds the (first)
1961 test with that name in that module, and converts it to a script. The
1962 example code is converted to regular Python code. The surrounding
1963 words and expected output are converted to comments:
1964
1965 >>> from test.test_doctest import test_doctest
1966 >>> name = 'test.test_doctest.test_doctest.sample_func'
1967 >>> print(doctest.testsource(test_doctest, name))
1968 # Blah blah
1969 #
1970 print(sample_func(22))
1971 # Expected:
1972 ## 44
1973 #
1974 # Yee ha!
1975 <BLANKLINE>
1976
1977 >>> name = 'test.test_doctest.test_doctest.SampleNewStyleClass'
1978 >>> print(doctest.testsource(test_doctest, name))
1979 print('1\n2\n3')
1980 # Expected:
1981 ## 1
1982 ## 2
1983 ## 3
1984 <BLANKLINE>
1985
1986 >>> name = 'test.test_doctest.test_doctest.SampleClass.a_classmethod'
1987 >>> print(doctest.testsource(test_doctest, name))
1988 print(SampleClass.a_classmethod(10))
1989 # Expected:
1990 ## 12
1991 print(SampleClass(0).a_classmethod(10))
1992 # Expected:
1993 ## 12
1994 <BLANKLINE>
1995 """
1996
1997 def test_debug(): r"""
1998
1999 Create a docstring that we want to debug:
2000
2001 >>> s = '''
2002 ... >>> x = 12
2003 ... >>> print(x)
2004 ... 12
2005 ... '''
2006
2007 Create some fake stdin input, to feed to the debugger:
2008
2009 >>> real_stdin = sys.stdin
2010 >>> sys.stdin = FakeInput(['next', 'print(x)', 'continue'])
2011
2012 Run the debugger on the docstring, and then restore sys.stdin.
2013
2014 >>> try: doctest.debug_src(s)
2015 ... finally: sys.stdin = real_stdin
2016 > <string>(1)<module>()
2017 (Pdb) next
2018 12
2019 --Return--
2020 > <string>(1)<module>()->None
2021 (Pdb) print(x)
2022 12
2023 (Pdb) continue
2024
2025 """
2026
2027 if not hasattr(sys, 'gettrace') or not sys.gettrace():
2028 def test_pdb_set_trace():
2029 """Using pdb.set_trace from a doctest.
2030
2031 You can use pdb.set_trace from a doctest. To do so, you must
2032 retrieve the set_trace function from the pdb module at the time
2033 you use it. The doctest module changes sys.stdout so that it can
2034 capture program output. It also temporarily replaces pdb.set_trace
2035 with a version that restores stdout. This is necessary for you to
2036 see debugger output.
2037
2038 >>> save_colorize = _colorize.COLORIZE
2039 >>> _colorize.COLORIZE = False
2040
2041 >>> doc = '''
2042 ... >>> x = 42
2043 ... >>> raise Exception('clé')
2044 ... Traceback (most recent call last):
2045 ... Exception: clé
2046 ... >>> import pdb; pdb.set_trace()
2047 ... '''
2048 >>> parser = doctest.DocTestParser()
2049 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "[email protected]", 0)
2050 >>> runner = doctest.DocTestRunner(verbose=False)
2051
2052 To demonstrate this, we'll create a fake standard input that
2053 captures our debugger input:
2054
2055 >>> real_stdin = sys.stdin
2056 >>> sys.stdin = FakeInput([
2057 ... 'print(x)', # print data defined by the example
2058 ... 'continue', # stop debugging
2059 ... ''])
2060
2061 >>> try: runner.run(test)
2062 ... finally: sys.stdin = real_stdin
2063 > <doctest foo-bar@baz[2]>(1)<module>()
2064 -> import pdb; pdb.set_trace()
2065 (Pdb) print(x)
2066 42
2067 (Pdb) continue
2068 TestResults(failed=0, attempted=3)
2069
2070 You can also put pdb.set_trace in a function called from a test:
2071
2072 >>> def calls_set_trace():
2073 ... y=2
2074 ... import pdb; pdb.set_trace()
2075
2076 >>> doc = '''
2077 ... >>> x=1
2078 ... >>> calls_set_trace()
2079 ... '''
2080 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "[email protected]", 0)
2081 >>> real_stdin = sys.stdin
2082 >>> sys.stdin = FakeInput([
2083 ... 'print(y)', # print data defined in the function
2084 ... 'up', # out of function
2085 ... 'print(x)', # print data defined by the example
2086 ... 'continue', # stop debugging
2087 ... ''])
2088
2089 >>> try:
2090 ... runner.run(test)
2091 ... finally:
2092 ... sys.stdin = real_stdin
2093 > <doctest test.test_doctest.test_doctest.test_pdb_set_trace[9]>(3)calls_set_trace()
2094 -> import pdb; pdb.set_trace()
2095 (Pdb) print(y)
2096 2
2097 (Pdb) up
2098 > <doctest foo-bar@baz[1]>(1)<module>()
2099 -> calls_set_trace()
2100 (Pdb) print(x)
2101 1
2102 (Pdb) continue
2103 TestResults(failed=0, attempted=2)
2104
2105 During interactive debugging, source code is shown, even for
2106 doctest examples:
2107
2108 >>> doc = '''
2109 ... >>> def f(x):
2110 ... ... g(x*2)
2111 ... >>> def g(x):
2112 ... ... print(x+3)
2113 ... ... import pdb; pdb.set_trace()
2114 ... >>> f(3)
2115 ... '''
2116 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "[email protected]", 0)
2117 >>> real_stdin = sys.stdin
2118 >>> sys.stdin = FakeInput([
2119 ... 'step', # return event of g
2120 ... 'list', # list source from example 2
2121 ... 'next', # return from g()
2122 ... 'list', # list source from example 1
2123 ... 'next', # return from f()
2124 ... 'list', # list source from example 3
2125 ... 'continue', # stop debugging
2126 ... ''])
2127 >>> try: runner.run(test)
2128 ... finally: sys.stdin = real_stdin
2129 ... # doctest: +NORMALIZE_WHITESPACE
2130 > <doctest foo-bar@baz[1]>(3)g()
2131 -> import pdb; pdb.set_trace()
2132 (Pdb) step
2133 --Return--
2134 > <doctest foo-bar@baz[1]>(3)g()->None
2135 -> import pdb; pdb.set_trace()
2136 (Pdb) list
2137 1 def g(x):
2138 2 print(x+3)
2139 3 -> import pdb; pdb.set_trace()
2140 [EOF]
2141 (Pdb) next
2142 --Return--
2143 > <doctest foo-bar@baz[0]>(2)f()->None
2144 -> g(x*2)
2145 (Pdb) list
2146 1 def f(x):
2147 2 -> g(x*2)
2148 [EOF]
2149 (Pdb) next
2150 --Return--
2151 > <doctest foo-bar@baz[2]>(1)<module>()->None
2152 -> f(3)
2153 (Pdb) list
2154 1 -> f(3)
2155 [EOF]
2156 (Pdb) continue
2157 **********************************************************************
2158 File "[email protected]", line 7, in foo-bar@baz
2159 Failed example:
2160 f(3)
2161 Expected nothing
2162 Got:
2163 9
2164 TestResults(failed=1, attempted=3)
2165
2166 >>> _colorize.COLORIZE = save_colorize
2167 """
2168
2169 def test_pdb_set_trace_nested():
2170 """This illustrates more-demanding use of set_trace with nested functions.
2171
2172 >>> class C(object):
2173 ... def calls_set_trace(self):
2174 ... y = 1
2175 ... import pdb; pdb.set_trace()
2176 ... self.f1()
2177 ... y = 2
2178 ... def f1(self):
2179 ... x = 1
2180 ... self.f2()
2181 ... x = 2
2182 ... def f2(self):
2183 ... z = 1
2184 ... z = 2
2185
2186 >>> calls_set_trace = C().calls_set_trace
2187
2188 >>> doc = '''
2189 ... >>> a = 1
2190 ... >>> calls_set_trace()
2191 ... '''
2192 >>> parser = doctest.DocTestParser()
2193 >>> runner = doctest.DocTestRunner(verbose=False)
2194 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "[email protected]", 0)
2195 >>> real_stdin = sys.stdin
2196 >>> sys.stdin = FakeInput([
2197 ... 'step',
2198 ... 'print(y)', # print data defined in the function
2199 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
2200 ... 'up', 'print(x)',
2201 ... 'up', 'print(y)',
2202 ... 'up', 'print(foo)',
2203 ... 'continue', # stop debugging
2204 ... ''])
2205
2206 >>> try:
2207 ... runner.run(test)
2208 ... finally:
2209 ... sys.stdin = real_stdin
2210 ... # doctest: +REPORT_NDIFF
2211 > <doctest test.test_doctest.test_doctest.test_pdb_set_trace_nested[0]>(4)calls_set_trace()
2212 -> import pdb; pdb.set_trace()
2213 (Pdb) step
2214 > <doctest test.test_doctest.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2215 -> self.f1()
2216 (Pdb) print(y)
2217 1
2218 (Pdb) step
2219 --Call--
2220 > <doctest test.test_doctest.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
2221 -> def f1(self):
2222 (Pdb) step
2223 > <doctest test.test_doctest.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
2224 -> x = 1
2225 (Pdb) step
2226 > <doctest test.test_doctest.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2227 -> self.f2()
2228 (Pdb) step
2229 --Call--
2230 > <doctest test.test_doctest.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
2231 -> def f2(self):
2232 (Pdb) step
2233 > <doctest test.test_doctest.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
2234 -> z = 1
2235 (Pdb) step
2236 > <doctest test.test_doctest.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
2237 -> z = 2
2238 (Pdb) print(z)
2239 1
2240 (Pdb) up
2241 > <doctest test.test_doctest.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
2242 -> self.f2()
2243 (Pdb) print(x)
2244 1
2245 (Pdb) up
2246 > <doctest test.test_doctest.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2247 -> self.f1()
2248 (Pdb) print(y)
2249 1
2250 (Pdb) up
2251 > <doctest foo-bar@baz[1]>(1)<module>()
2252 -> calls_set_trace()
2253 (Pdb) print(foo)
2254 *** NameError: name 'foo' is not defined
2255 (Pdb) continue
2256 TestResults(failed=0, attempted=2)
2257 """
2258
2259 def test_DocTestSuite():
2260 """DocTestSuite creates a unittest test suite from a doctest.
2261
2262 We create a Suite by providing a module. A module can be provided
2263 by passing a module object:
2264
2265 >>> import unittest
2266 >>> import test.test_doctest.sample_doctest
2267 >>> suite = doctest.DocTestSuite(test.test_doctest.sample_doctest)
2268 >>> result = suite.run(unittest.TestResult())
2269 >>> result
2270 <unittest.result.TestResult run=9 errors=0 failures=4>
2271 >>> for tst, _ in result.failures:
2272 ... print(tst)
2273 bad (test.test_doctest.sample_doctest.__test__)
2274 foo (test.test_doctest.sample_doctest)
2275 test_silly_setup (test.test_doctest.sample_doctest)
2276 y_is_one (test.test_doctest.sample_doctest)
2277
2278 We can also supply the module by name:
2279
2280 >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest')
2281 >>> result = suite.run(unittest.TestResult())
2282 >>> result
2283 <unittest.result.TestResult run=9 errors=0 failures=4>
2284
2285 The module need not contain any doctest examples:
2286
2287 >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest_no_doctests')
2288 >>> suite.run(unittest.TestResult())
2289 <unittest.result.TestResult run=0 errors=0 failures=0>
2290
2291 The module need not contain any docstrings either:
2292
2293 >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest_no_docstrings')
2294 >>> suite.run(unittest.TestResult())
2295 <unittest.result.TestResult run=0 errors=0 failures=0>
2296
2297 If all examples in a docstring are skipped, unittest will report it as a
2298 skipped test:
2299
2300 >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest_skip')
2301 >>> result = suite.run(unittest.TestResult())
2302 >>> result
2303 <unittest.result.TestResult run=6 errors=0 failures=2>
2304 >>> len(result.skipped)
2305 2
2306 >>> for tst, _ in result.skipped:
2307 ... print(tst)
2308 double_skip (test.test_doctest.sample_doctest_skip)
2309 single_skip (test.test_doctest.sample_doctest_skip)
2310 >>> for tst, _ in result.failures:
2311 ... print(tst)
2312 no_skip_fail (test.test_doctest.sample_doctest_skip)
2313 partial_skip_fail (test.test_doctest.sample_doctest_skip)
2314
2315 We can use the current module:
2316
2317 >>> suite = test.test_doctest.sample_doctest.test_suite()
2318 >>> suite.run(unittest.TestResult())
2319 <unittest.result.TestResult run=9 errors=0 failures=4>
2320
2321 We can also provide a DocTestFinder:
2322
2323 >>> finder = doctest.DocTestFinder()
2324 >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest',
2325 ... test_finder=finder)
2326 >>> suite.run(unittest.TestResult())
2327 <unittest.result.TestResult run=9 errors=0 failures=4>
2328
2329 The DocTestFinder need not return any tests:
2330
2331 >>> finder = doctest.DocTestFinder()
2332 >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest_no_docstrings',
2333 ... test_finder=finder)
2334 >>> suite.run(unittest.TestResult())
2335 <unittest.result.TestResult run=0 errors=0 failures=0>
2336
2337 We can supply global variables. If we pass globs, they will be
2338 used instead of the module globals. Here we'll pass an empty
2339 globals, triggering an extra error:
2340
2341 >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest', globs={})
2342 >>> suite.run(unittest.TestResult())
2343 <unittest.result.TestResult run=9 errors=0 failures=5>
2344
2345 Alternatively, we can provide extra globals. Here we'll make an
2346 error go away by providing an extra global variable:
2347
2348 >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest',
2349 ... extraglobs={'y': 1})
2350 >>> suite.run(unittest.TestResult())
2351 <unittest.result.TestResult run=9 errors=0 failures=3>
2352
2353 You can pass option flags. Here we'll cause an extra error
2354 by disabling the blank-line feature:
2355
2356 >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest',
2357 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2358 >>> suite.run(unittest.TestResult())
2359 <unittest.result.TestResult run=9 errors=0 failures=5>
2360
2361 You can supply setUp and tearDown functions:
2362
2363 >>> def setUp(t):
2364 ... from test.test_doctest import test_doctest
2365 ... test_doctest.sillySetup = True
2366
2367 >>> def tearDown(t):
2368 ... from test.test_doctest import test_doctest
2369 ... del test_doctest.sillySetup
2370
2371 Here, we installed a silly variable that the test expects:
2372
2373 >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest',
2374 ... setUp=setUp, tearDown=tearDown)
2375 >>> suite.run(unittest.TestResult())
2376 <unittest.result.TestResult run=9 errors=0 failures=3>
2377
2378 But the tearDown restores sanity:
2379
2380 >>> from test.test_doctest import test_doctest
2381 >>> test_doctest.sillySetup
2382 Traceback (most recent call last):
2383 ...
2384 AttributeError: module 'test.test_doctest.test_doctest' has no attribute 'sillySetup'
2385
2386 The setUp and tearDown functions are passed test objects. Here
2387 we'll use the setUp function to supply the missing variable y:
2388
2389 >>> def setUp(test):
2390 ... test.globs['y'] = 1
2391
2392 >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest', setUp=setUp)
2393 >>> suite.run(unittest.TestResult())
2394 <unittest.result.TestResult run=9 errors=0 failures=3>
2395
2396 Here, we didn't need to use a tearDown function because we
2397 modified the test globals, which are a copy of the
2398 sample_doctest module dictionary. The test globals are
2399 automatically cleared for us after a test.
2400 """
2401
2402 def test_DocTestSuite_errors():
2403 """Tests for error reporting in DocTestSuite.
2404
2405 >>> import unittest
2406 >>> import test.test_doctest.sample_doctest_errors as mod
2407 >>> suite = doctest.DocTestSuite(mod)
2408 >>> result = suite.run(unittest.TestResult())
2409 >>> result
2410 <unittest.result.TestResult run=4 errors=0 failures=4>
2411 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
2412 Traceback (most recent call last):
2413 File ...
2414 raise self.failureException(self.format_failure(new.getvalue()))
2415 AssertionError: Failed doctest test for test.test_doctest.sample_doctest_errors
2416 File "...sample_doctest_errors.py", line 0, in sample_doctest_errors
2417 <BLANKLINE>
2418 ----------------------------------------------------------------------
2419 File "...sample_doctest_errors.py", line 5, in test.test_doctest.sample_doctest_errors
2420 Failed example:
2421 2 + 2
2422 Expected:
2423 5
2424 Got:
2425 4
2426 ----------------------------------------------------------------------
2427 File "...sample_doctest_errors.py", line 7, in test.test_doctest.sample_doctest_errors
2428 Failed example:
2429 1/0
2430 Exception raised:
2431 Traceback (most recent call last):
2432 File ...
2433 exec(compile(example.source, filename, "single",
2434 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2435 compileflags, True), test.globs)
2436 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2437 File "<doctest test.test_doctest.sample_doctest_errors[1]>", line 1, in <module>
2438 1/0
2439 ~^~
2440 ZeroDivisionError: division by zero
2441 <BLANKLINE>
2442 <BLANKLINE>
2443 >>> print(result.failures[1][1]) # doctest: +ELLIPSIS
2444 Traceback (most recent call last):
2445 File ...
2446 raise self.failureException(self.format_failure(new.getvalue()))
2447 AssertionError: Failed doctest test for test.test_doctest.sample_doctest_errors.__test__.bad
2448 File "...sample_doctest_errors.py", line unknown line number, in bad
2449 <BLANKLINE>
2450 ----------------------------------------------------------------------
2451 File "...sample_doctest_errors.py", line ?, in test.test_doctest.sample_doctest_errors.__test__.bad
2452 Failed example:
2453 2 + 2
2454 Expected:
2455 5
2456 Got:
2457 4
2458 ----------------------------------------------------------------------
2459 File "...sample_doctest_errors.py", line ?, in test.test_doctest.sample_doctest_errors.__test__.bad
2460 Failed example:
2461 1/0
2462 Exception raised:
2463 Traceback (most recent call last):
2464 File ...
2465 exec(compile(example.source, filename, "single",
2466 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2467 compileflags, True), test.globs)
2468 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2469 File "<doctest test.test_doctest.sample_doctest_errors.__test__.bad[1]>", line 1, in <module>
2470 1/0
2471 ~^~
2472 ZeroDivisionError: division by zero
2473 <BLANKLINE>
2474 <BLANKLINE>
2475 >>> print(result.failures[2][1]) # doctest: +ELLIPSIS
2476 Traceback (most recent call last):
2477 File ...
2478 raise self.failureException(self.format_failure(new.getvalue()))
2479 AssertionError: Failed doctest test for test.test_doctest.sample_doctest_errors.errors
2480 File "...sample_doctest_errors.py", line 14, in errors
2481 <BLANKLINE>
2482 ----------------------------------------------------------------------
2483 File "...sample_doctest_errors.py", line 16, in test.test_doctest.sample_doctest_errors.errors
2484 Failed example:
2485 2 + 2
2486 Expected:
2487 5
2488 Got:
2489 4
2490 ----------------------------------------------------------------------
2491 File "...sample_doctest_errors.py", line 18, in test.test_doctest.sample_doctest_errors.errors
2492 Failed example:
2493 1/0
2494 Exception raised:
2495 Traceback (most recent call last):
2496 File ...
2497 exec(compile(example.source, filename, "single",
2498 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2499 compileflags, True), test.globs)
2500 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2501 File "<doctest test.test_doctest.sample_doctest_errors.errors[1]>", line 1, in <module>
2502 1/0
2503 ~^~
2504 ZeroDivisionError: division by zero
2505 ----------------------------------------------------------------------
2506 File "...sample_doctest_errors.py", line 23, in test.test_doctest.sample_doctest_errors.errors
2507 Failed example:
2508 f()
2509 Exception raised:
2510 Traceback (most recent call last):
2511 File ...
2512 exec(compile(example.source, filename, "single",
2513 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2514 compileflags, True), test.globs)
2515 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2516 File "<doctest test.test_doctest.sample_doctest_errors.errors[3]>", line 1, in <module>
2517 f()
2518 ~^^
2519 File "<doctest test.test_doctest.sample_doctest_errors.errors[2]>", line 2, in f
2520 2 + '2'
2521 ~~^~~~~
2522 TypeError: ...
2523 ----------------------------------------------------------------------
2524 File "...sample_doctest_errors.py", line 25, in test.test_doctest.sample_doctest_errors.errors
2525 Failed example:
2526 g()
2527 Exception raised:
2528 Traceback (most recent call last):
2529 File ...
2530 exec(compile(example.source, filename, "single",
2531 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2532 compileflags, True), test.globs)
2533 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2534 File "<doctest test.test_doctest.sample_doctest_errors.errors[4]>", line 1, in <module>
2535 g()
2536 ~^^
2537 File "...sample_doctest_errors.py", line 12, in g
2538 [][0] # line 12
2539 ~~^^^
2540 IndexError: list index out of range
2541 <BLANKLINE>
2542 <BLANKLINE>
2543 >>> print(result.failures[3][1]) # doctest: +ELLIPSIS
2544 Traceback (most recent call last):
2545 File ...
2546 raise self.failureException(self.format_failure(new.getvalue()))
2547 AssertionError: Failed doctest test for test.test_doctest.sample_doctest_errors.syntax_error
2548 File "...sample_doctest_errors.py", line 29, in syntax_error
2549 <BLANKLINE>
2550 ----------------------------------------------------------------------
2551 File "...sample_doctest_errors.py", line 31, in test.test_doctest.sample_doctest_errors.syntax_error
2552 Failed example:
2553 2+*3
2554 Exception raised:
2555 Traceback (most recent call last):
2556 File ...
2557 exec(compile(example.source, filename, "single",
2558 ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2559 compileflags, True), test.globs)
2560 ^^^^^^^^^^^^^^^^^^^
2561 File "<doctest test.test_doctest.sample_doctest_errors.syntax_error[0]>", line 1
2562 2+*3
2563 ^
2564 SyntaxError: invalid syntax
2565 <BLANKLINE>
2566 <BLANKLINE>
2567 """
2568
2569 def test_DocFileSuite():
2570 """We can test tests found in text files using a DocFileSuite.
2571
2572 We create a suite by providing the names of one or more text
2573 files that include examples:
2574
2575 >>> import unittest
2576 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2577 ... 'test_doctest2.txt',
2578 ... 'test_doctest4.txt')
2579 >>> suite.run(unittest.TestResult())
2580 <unittest.result.TestResult run=3 errors=0 failures=2>
2581
2582 The test files are looked for in the directory containing the
2583 calling module. A package keyword argument can be provided to
2584 specify a different relative location.
2585
2586 >>> import unittest
2587 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2588 ... 'test_doctest2.txt',
2589 ... 'test_doctest4.txt',
2590 ... package='test.test_doctest')
2591 >>> suite.run(unittest.TestResult())
2592 <unittest.result.TestResult run=3 errors=0 failures=2>
2593
2594 Support for using a package's __loader__.get_data() is also
2595 provided.
2596
2597 >>> import unittest, pkgutil, test
2598 >>> added_loader = False
2599 >>> if not hasattr(test, '__loader__'):
2600 ... test.__loader__ = pkgutil.get_loader(test)
2601 ... added_loader = True
2602 >>> try:
2603 ... suite = doctest.DocFileSuite('test_doctest.txt',
2604 ... 'test_doctest2.txt',
2605 ... 'test_doctest4.txt',
2606 ... package='test.test_doctest')
2607 ... suite.run(unittest.TestResult())
2608 ... finally:
2609 ... if added_loader:
2610 ... del test.__loader__
2611 <unittest.result.TestResult run=3 errors=0 failures=2>
2612
2613 '/' should be used as a path separator. It will be converted
2614 to a native separator at run time:
2615
2616 >>> suite = doctest.DocFileSuite('../test_doctest/test_doctest.txt')
2617 >>> suite.run(unittest.TestResult())
2618 <unittest.result.TestResult run=1 errors=0 failures=1>
2619
2620 If DocFileSuite is used from an interactive session, then files
2621 are resolved relative to the directory of sys.argv[0]:
2622
2623 >>> import types, os.path
2624 >>> from test.test_doctest import test_doctest
2625 >>> save_argv = sys.argv
2626 >>> sys.argv = [test_doctest.__file__]
2627 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2628 ... package=types.ModuleType('__main__'))
2629 >>> sys.argv = save_argv
2630
2631 By setting `module_relative=False`, os-specific paths may be
2632 used (including absolute paths and paths relative to the
2633 working directory):
2634
2635 >>> # Get the absolute path of the test package.
2636 >>> test_doctest_path = os.path.abspath(test_doctest.__file__)
2637 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2638
2639 >>> # Use it to find the absolute path of test_doctest.txt.
2640 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2641
2642 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
2643 >>> suite.run(unittest.TestResult())
2644 <unittest.result.TestResult run=1 errors=0 failures=1>
2645
2646 It is an error to specify `package` when `module_relative=False`:
2647
2648 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2649 ... package='test')
2650 Traceback (most recent call last):
2651 ValueError: Package may only be specified for module-relative paths.
2652
2653 If all examples in a file are skipped, unittest will report it as a
2654 skipped test:
2655
2656 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2657 ... 'test_doctest4.txt',
2658 ... 'test_doctest_skip.txt',
2659 ... 'test_doctest_skip2.txt')
2660 >>> result = suite.run(unittest.TestResult())
2661 >>> result
2662 <unittest.result.TestResult run=4 errors=0 failures=1>
2663 >>> len(result.skipped)
2664 1
2665 >>> for tst, _ in result.skipped: # doctest: +ELLIPSIS
2666 ... print('=', tst)
2667 = ...test_doctest_skip.txt
2668
2669 You can specify initial global variables:
2670
2671 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2672 ... 'test_doctest2.txt',
2673 ... 'test_doctest4.txt',
2674 ... globs={'favorite_color': 'blue'})
2675 >>> suite.run(unittest.TestResult())
2676 <unittest.result.TestResult run=3 errors=0 failures=1>
2677
2678 In this case, we supplied a missing favorite color. You can
2679 provide doctest options:
2680
2681 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2682 ... 'test_doctest2.txt',
2683 ... 'test_doctest4.txt',
2684 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2685 ... globs={'favorite_color': 'blue'})
2686 >>> suite.run(unittest.TestResult())
2687 <unittest.result.TestResult run=3 errors=0 failures=2>
2688
2689 And, you can provide setUp and tearDown functions:
2690
2691 >>> def setUp(t):
2692 ... from test.test_doctest import test_doctest
2693 ... test_doctest.sillySetup = True
2694
2695 >>> def tearDown(t):
2696 ... from test.test_doctest import test_doctest
2697 ... del test_doctest.sillySetup
2698
2699 Here, we installed a silly variable that the test expects:
2700
2701 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2702 ... 'test_doctest2.txt',
2703 ... 'test_doctest4.txt',
2704 ... setUp=setUp, tearDown=tearDown)
2705 >>> suite.run(unittest.TestResult())
2706 <unittest.result.TestResult run=3 errors=0 failures=1>
2707
2708 But the tearDown restores sanity:
2709
2710 >>> from test.test_doctest import test_doctest
2711 >>> test_doctest.sillySetup
2712 Traceback (most recent call last):
2713 ...
2714 AttributeError: module 'test.test_doctest.test_doctest' has no attribute 'sillySetup'
2715
2716 The setUp and tearDown functions are passed test objects.
2717 Here, we'll use a setUp function to set the favorite color in
2718 test_doctest.txt:
2719
2720 >>> def setUp(test):
2721 ... test.globs['favorite_color'] = 'blue'
2722
2723 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2724 >>> suite.run(unittest.TestResult())
2725 <unittest.result.TestResult run=1 errors=0 failures=0>
2726
2727 Here, we didn't need to use a tearDown function because we
2728 modified the test globals. The test globals are
2729 automatically cleared for us after a test.
2730
2731 Tests in a file run using `DocFileSuite` can also access the
2732 `__file__` global, which is set to the name of the file
2733 containing the tests:
2734
2735 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2736 >>> suite.run(unittest.TestResult())
2737 <unittest.result.TestResult run=1 errors=0 failures=0>
2738
2739 If the tests contain non-ASCII characters, we have to specify which
2740 encoding the file is encoded with. We do so by using the `encoding`
2741 parameter:
2742
2743 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2744 ... 'test_doctest2.txt',
2745 ... 'test_doctest4.txt',
2746 ... encoding='utf-8')
2747 >>> suite.run(unittest.TestResult())
2748 <unittest.result.TestResult run=3 errors=0 failures=2>
2749 """
2750
2751 def test_DocFileSuite_errors():
2752 """Tests for error reporting in DocTestSuite.
2753
2754 >>> import unittest
2755 >>> suite = doctest.DocFileSuite('test_doctest_errors.txt')
2756 >>> result = suite.run(unittest.TestResult())
2757 >>> result
2758 <unittest.result.TestResult run=1 errors=0 failures=1>
2759 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
2760 Traceback (most recent call last):
2761 File ...
2762 raise self.failureException(self.format_failure(new.getvalue()))
2763 AssertionError: Failed doctest test for test_doctest_errors.txt
2764 File "...test_doctest_errors.txt", line 0
2765 <BLANKLINE>
2766 ----------------------------------------------------------------------
2767 File "...test_doctest_errors.txt", line 4, in test_doctest_errors.txt
2768 Failed example:
2769 2 + 2
2770 Expected:
2771 5
2772 Got:
2773 4
2774 ----------------------------------------------------------------------
2775 File "...test_doctest_errors.txt", line 6, in test_doctest_errors.txt
2776 Failed example:
2777 1/0
2778 Exception raised:
2779 Traceback (most recent call last):
2780 File ...
2781 exec(compile(example.source, filename, "single",
2782 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2783 compileflags, True), test.globs)
2784 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2785 File "<doctest test_doctest_errors.txt[1]>", line 1, in <module>
2786 1/0
2787 ~^~
2788 ZeroDivisionError: division by zero
2789 ----------------------------------------------------------------------
2790 File "...test_doctest_errors.txt", line 11, in test_doctest_errors.txt
2791 Failed example:
2792 f()
2793 Exception raised:
2794 Traceback (most recent call last):
2795 File ...
2796 exec(compile(example.source, filename, "single",
2797 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2798 compileflags, True), test.globs)
2799 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2800 File "<doctest test_doctest_errors.txt[3]>", line 1, in <module>
2801 f()
2802 ~^^
2803 File "<doctest test_doctest_errors.txt[2]>", line 2, in f
2804 2 + '2'
2805 ~~^~~~~
2806 TypeError: ...
2807 ----------------------------------------------------------------------
2808 File "...test_doctest_errors.txt", line 13, in test_doctest_errors.txt
2809 Failed example:
2810 2+*3
2811 Exception raised:
2812 Traceback (most recent call last):
2813 File ...
2814 exec(compile(example.source, filename, "single",
2815 ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2816 compileflags, True), test.globs)
2817 ^^^^^^^^^^^^^^^^^^^
2818 File "<doctest test_doctest_errors.txt[4]>", line 1
2819 2+*3
2820 ^
2821 SyntaxError: invalid syntax
2822 <BLANKLINE>
2823 <BLANKLINE>
2824 """
2825
2826 def test_trailing_space_in_test():
2827 """
2828 Trailing spaces in expected output are significant:
2829
2830 >>> x, y = 'foo', ''
2831 >>> print(x, y)
2832 foo \n
2833 """
2834
2835 class Wrapper:
2836 def __init__(self, func):
2837 self.func = func
2838 functools.update_wrapper(self, func)
2839
2840 def __call__(self, *args, **kwargs):
2841 self.func(*args, **kwargs)
2842
2843 @Wrapper
2844 def wrapped():
2845 """
2846 Docstrings in wrapped functions must be detected as well.
2847
2848 >>> 'one other test'
2849 'one other test'
2850 """
2851
2852 def test_look_in_unwrapped():
2853 """
2854 Ensure that wrapped doctests work correctly.
2855
2856 >>> import doctest
2857 >>> doctest.run_docstring_examples(
2858 ... wrapped, {}, name=wrapped.__name__, verbose=True)
2859 Finding tests in wrapped
2860 Trying:
2861 'one other test'
2862 Expecting:
2863 'one other test'
2864 ok
2865 """
2866
2867 @doctest_skip_if(support.check_impl_detail(cpython=False))
2868 def test_wrapped_c_func():
2869 """
2870 # https://github.com/python/cpython/issues/117692
2871 >>> import binascii
2872 >>> from test.test_doctest.decorator_mod import decorator
2873
2874 >>> c_func_wrapped = decorator(binascii.b2a_hex)
2875 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(c_func_wrapped)
2876 >>> for test in tests:
2877 ... print(test.lineno, test.name)
2878 None b2a_hex
2879 """
2880
2881 def test_unittest_reportflags():
2882 """Default unittest reporting flags can be set to control reporting
2883
2884 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2885 only the first failure of each test. First, we'll look at the
2886 output without the flag. The file test_doctest.txt file has two
2887 tests. They both fail if blank lines are disabled:
2888
2889 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2890 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2891 >>> import unittest
2892 >>> result = suite.run(unittest.TestResult())
2893 >>> result
2894 <unittest.result.TestResult run=1 errors=0 failures=1>
2895 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
2896 Traceback ...
2897 Failed example:
2898 favorite_color
2899 ...
2900 Failed example:
2901 if 1:
2902 ...
2903
2904 Note that we see both failures displayed.
2905
2906 >>> old = doctest.set_unittest_reportflags(
2907 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2908
2909 Now, when we run the test:
2910
2911 >>> result = suite.run(unittest.TestResult())
2912 >>> result
2913 <unittest.result.TestResult run=1 errors=0 failures=1>
2914 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
2915 Traceback ...
2916 Failed example:
2917 favorite_color
2918 Exception raised:
2919 ...
2920 NameError: name 'favorite_color' is not defined
2921 <BLANKLINE>
2922 <BLANKLINE>
2923
2924 We get only the first failure.
2925
2926 If we give any reporting options when we set up the tests,
2927 however:
2928
2929 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2930 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2931
2932 Then the default eporting options are ignored:
2933
2934 >>> result = suite.run(unittest.TestResult())
2935 >>> result
2936 <unittest.result.TestResult run=1 errors=0 failures=1>
2937
2938 *NOTE*: These doctest are intentionally not placed in raw string to depict
2939 the trailing whitespace using `\x20` in the diff below.
2940
2941 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
2942 Traceback ...
2943 Failed example:
2944 favorite_color
2945 ...
2946 Failed example:
2947 if 1:
2948 print('a')
2949 print()
2950 print('b')
2951 Differences (ndiff with -expected +actual):
2952 a
2953 - <BLANKLINE>
2954 +\x20
2955 b
2956 <BLANKLINE>
2957 <BLANKLINE>
2958
2959
2960 Test runners can restore the formatting flags after they run:
2961
2962 >>> ignored = doctest.set_unittest_reportflags(old)
2963
2964 """
2965
2966 def test_testfile(): r"""
2967 Tests for the `testfile()` function. This function runs all the
2968 doctest examples in a given file. In its simple invocation, it is
2969 called with the name of a file, which is taken to be relative to the
2970 calling module. The return value is (#failures, #tests).
2971
2972 We don't want color or `-v` in sys.argv for these tests.
2973
2974 >>> save_colorize = _colorize.COLORIZE
2975 >>> _colorize.COLORIZE = False
2976
2977 >>> save_argv = sys.argv
2978 >>> if '-v' in sys.argv:
2979 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2980
2981
2982 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2983 **********************************************************************
2984 File "...", line 6, in test_doctest.txt
2985 Failed example:
2986 favorite_color
2987 Exception raised:
2988 ...
2989 NameError: name 'favorite_color' is not defined
2990 **********************************************************************
2991 1 item had failures:
2992 1 of 2 in test_doctest.txt
2993 ***Test Failed*** 1 failure.
2994 TestResults(failed=1, attempted=2)
2995 >>> doctest.master = None # Reset master.
2996
2997 (Note: we'll be clearing doctest.master after each call to
2998 `doctest.testfile`, to suppress warnings about multiple tests with the
2999 same name.)
3000
3001 Globals may be specified with the `globs` and `extraglobs` parameters:
3002
3003 >>> globs = {'favorite_color': 'blue'}
3004 >>> doctest.testfile('test_doctest.txt', globs=globs)
3005 TestResults(failed=0, attempted=2)
3006 >>> doctest.master = None # Reset master.
3007
3008 >>> extraglobs = {'favorite_color': 'red'}
3009 >>> doctest.testfile('test_doctest.txt', globs=globs,
3010 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
3011 **********************************************************************
3012 File "...", line 6, in test_doctest.txt
3013 Failed example:
3014 favorite_color
3015 Expected:
3016 'blue'
3017 Got:
3018 'red'
3019 **********************************************************************
3020 1 item had failures:
3021 1 of 2 in test_doctest.txt
3022 ***Test Failed*** 1 failure.
3023 TestResults(failed=1, attempted=2)
3024 >>> doctest.master = None # Reset master.
3025
3026 The file may be made relative to a given module or package, using the
3027 optional `module_relative` parameter:
3028
3029 >>> doctest.testfile('test_doctest.txt', globs=globs,
3030 ... module_relative='test')
3031 TestResults(failed=0, attempted=2)
3032 >>> doctest.master = None # Reset master.
3033
3034 Verbosity can be increased with the optional `verbose` parameter:
3035
3036 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
3037 Trying:
3038 favorite_color
3039 Expecting:
3040 'blue'
3041 ok
3042 Trying:
3043 if 1:
3044 print('a')
3045 print()
3046 print('b')
3047 Expecting:
3048 a
3049 <BLANKLINE>
3050 b
3051 ok
3052 1 item passed all tests:
3053 2 tests in test_doctest.txt
3054 2 tests in 1 item.
3055 2 passed.
3056 Test passed.
3057 TestResults(failed=0, attempted=2)
3058 >>> doctest.master = None # Reset master.
3059
3060 The name of the test may be specified with the optional `name`
3061 parameter:
3062
3063 >>> doctest.testfile('test_doctest.txt', name='newname')
3064 ... # doctest: +ELLIPSIS
3065 **********************************************************************
3066 File "...", line 6, in newname
3067 ...
3068 TestResults(failed=1, attempted=2)
3069 >>> doctest.master = None # Reset master.
3070
3071 The summary report may be suppressed with the optional `report`
3072 parameter:
3073
3074 >>> doctest.testfile('test_doctest.txt', report=False)
3075 ... # doctest: +ELLIPSIS
3076 **********************************************************************
3077 File "...", line 6, in test_doctest.txt
3078 Failed example:
3079 favorite_color
3080 Exception raised:
3081 ...
3082 NameError: name 'favorite_color' is not defined
3083 TestResults(failed=1, attempted=2)
3084 >>> doctest.master = None # Reset master.
3085
3086 The optional keyword argument `raise_on_error` can be used to raise an
3087 exception on the first error (which may be useful for postmortem
3088 debugging):
3089
3090 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
3091 ... # doctest: +ELLIPSIS
3092 Traceback (most recent call last):
3093 doctest.UnexpectedException: ...
3094 >>> doctest.master = None # Reset master.
3095
3096 If the tests contain non-ASCII characters, the tests might fail, since
3097 it's unknown which encoding is used. The encoding can be specified
3098 using the optional keyword argument `encoding`:
3099
3100 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
3101 **********************************************************************
3102 File "...", line 7, in test_doctest4.txt
3103 Failed example:
3104 '...'
3105 Expected:
3106 'f\xf6\xf6'
3107 Got:
3108 'f\xc3\xb6\xc3\xb6'
3109 **********************************************************************
3110 ...
3111 **********************************************************************
3112 1 item had failures:
3113 2 of 2 in test_doctest4.txt
3114 ***Test Failed*** 2 failures.
3115 TestResults(failed=2, attempted=2)
3116 >>> doctest.master = None # Reset master.
3117
3118 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
3119 TestResults(failed=0, attempted=2)
3120 >>> doctest.master = None # Reset master.
3121
3122 Test the verbose output:
3123
3124 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
3125 Trying:
3126 'föö'
3127 Expecting:
3128 'f\xf6\xf6'
3129 ok
3130 Trying:
3131 'bąr'
3132 Expecting:
3133 'b\u0105r'
3134 ok
3135 1 item passed all tests:
3136 2 tests in test_doctest4.txt
3137 2 tests in 1 item.
3138 2 passed.
3139 Test passed.
3140 TestResults(failed=0, attempted=2)
3141 >>> doctest.master = None # Reset master.
3142 >>> sys.argv = save_argv
3143 >>> _colorize.COLORIZE = save_colorize
3144 """
3145
3146 def test_testfile_errors(): r"""
3147 Tests for error reporting in the testfile() function.
3148
3149 >>> doctest.testfile('test_doctest_errors.txt', verbose=False) # doctest: +ELLIPSIS
3150 **********************************************************************
3151 File "...test_doctest_errors.txt", line 4, in test_doctest_errors.txt
3152 Failed example:
3153 2 + 2
3154 Expected:
3155 5
3156 Got:
3157 4
3158 **********************************************************************
3159 File "...test_doctest_errors.txt", line 6, in test_doctest_errors.txt
3160 Failed example:
3161 1/0
3162 Exception raised:
3163 Traceback (most recent call last):
3164 File ...
3165 exec(compile(example.source, filename, "single",
3166 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3167 compileflags, True), test.globs)
3168 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3169 File "<doctest test_doctest_errors.txt[1]>", line 1, in <module>
3170 1/0
3171 ~^~
3172 ZeroDivisionError: division by zero
3173 **********************************************************************
3174 File "...test_doctest_errors.txt", line 11, in test_doctest_errors.txt
3175 Failed example:
3176 f()
3177 Exception raised:
3178 Traceback (most recent call last):
3179 File ...
3180 exec(compile(example.source, filename, "single",
3181 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3182 compileflags, True), test.globs)
3183 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3184 File "<doctest test_doctest_errors.txt[3]>", line 1, in <module>
3185 f()
3186 ~^^
3187 File "<doctest test_doctest_errors.txt[2]>", line 2, in f
3188 2 + '2'
3189 ~~^~~~~
3190 TypeError: ...
3191 **********************************************************************
3192 File "...test_doctest_errors.txt", line 13, in test_doctest_errors.txt
3193 Failed example:
3194 2+*3
3195 Exception raised:
3196 Traceback (most recent call last):
3197 File ...
3198 exec(compile(example.source, filename, "single",
3199 ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3200 compileflags, True), test.globs)
3201 ^^^^^^^^^^^^^^^^^^^
3202 File "<doctest test_doctest_errors.txt[4]>", line 1
3203 2+*3
3204 ^
3205 SyntaxError: invalid syntax
3206 **********************************************************************
3207 1 item had failures:
3208 4 of 5 in test_doctest_errors.txt
3209 ***Test Failed*** 4 failures.
3210 TestResults(failed=4, attempted=5)
3211 """
3212
3213 class TestImporter(importlib.abc.MetaPathFinder):
3214
3215 def find_spec(self, fullname, path, target=None):
3216 return importlib.util.spec_from_file_location(fullname, path, loader=self)
3217
3218 def get_data(self, path):
3219 with open(path, mode='rb') as f:
3220 return f.read()
3221
3222 def exec_module(self, module):
3223 raise ImportError
3224
3225 def create_module(self, spec):
3226 return None
3227
3228 class TestHook:
3229
3230 def __init__(self, pathdir):
3231 self.sys_path = sys.path[:]
3232 self.meta_path = sys.meta_path[:]
3233 self.path_hooks = sys.path_hooks[:]
3234 sys.path.append(pathdir)
3235 sys.path_importer_cache.clear()
3236 self.modules_before = sys.modules.copy()
3237 self.importer = TestImporter()
3238 sys.meta_path.append(self.importer)
3239
3240 def remove(self):
3241 sys.path[:] = self.sys_path
3242 sys.meta_path[:] = self.meta_path
3243 sys.path_hooks[:] = self.path_hooks
3244 sys.path_importer_cache.clear()
3245 sys.modules.clear()
3246 sys.modules.update(self.modules_before)
3247
3248
3249 @contextlib.contextmanager
3250 def test_hook(pathdir):
3251 hook = TestHook(pathdir)
3252 try:
3253 yield hook
3254 finally:
3255 hook.remove()
3256
3257
3258 def test_lineendings(): r"""
3259 *nix systems use \n line endings, while Windows systems use \r\n, and
3260 old Mac systems used \r, which Python still recognizes as a line ending. Python
3261 handles this using universal newline mode for reading files. Let's make
3262 sure doctest does so (issue 8473) by creating temporary test files using each
3263 of the three line disciplines. At least one will not match either the universal
3264 newline \n or os.linesep for the platform the test is run on.
3265
3266 Windows line endings first:
3267
3268 >>> import tempfile, os
3269 >>> fn = tempfile.mktemp()
3270 >>> with open(fn, 'wb') as f:
3271 ... f.write(b'Test:\r\n\r\n >>> x = 1 + 1\r\n\r\nDone.\r\n')
3272 35
3273 >>> doctest.testfile(fn, module_relative=False, verbose=False)
3274 TestResults(failed=0, attempted=1)
3275 >>> os.remove(fn)
3276
3277 And now *nix line endings:
3278
3279 >>> fn = tempfile.mktemp()
3280 >>> with open(fn, 'wb') as f:
3281 ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
3282 30
3283 >>> doctest.testfile(fn, module_relative=False, verbose=False)
3284 TestResults(failed=0, attempted=1)
3285 >>> os.remove(fn)
3286
3287 And finally old Mac line endings:
3288
3289 >>> fn = tempfile.mktemp()
3290 >>> with open(fn, 'wb') as f:
3291 ... f.write(b'Test:\r\r >>> x = 1 + 1\r\rDone.\r')
3292 30
3293 >>> doctest.testfile(fn, module_relative=False, verbose=False)
3294 TestResults(failed=0, attempted=1)
3295 >>> os.remove(fn)
3296
3297 Now we test with a package loader that has a get_data method, since that
3298 bypasses the standard universal newline handling so doctest has to do the
3299 newline conversion itself; let's make sure it does so correctly (issue 1812).
3300 We'll write a file inside the package that has all three kinds of line endings
3301 in it, and use a package hook to install a custom loader; on any platform,
3302 at least one of the line endings will raise a ValueError for inconsistent
3303 whitespace if doctest does not correctly do the newline conversion.
3304
3305 >>> from test.support import os_helper
3306 >>> import shutil
3307 >>> dn = tempfile.mkdtemp()
3308 >>> pkg = os.path.join(dn, "doctest_testpkg")
3309 >>> os.mkdir(pkg)
3310 >>> os_helper.create_empty_file(os.path.join(pkg, "__init__.py"))
3311 >>> fn = os.path.join(pkg, "doctest_testfile.txt")
3312 >>> with open(fn, 'wb') as f:
3313 ... f.write(
3314 ... b'Test:\r\n\r\n'
3315 ... b' >>> x = 1 + 1\r\n\r\n'
3316 ... b'Done.\r\n'
3317 ... b'Test:\n\n'
3318 ... b' >>> x = 1 + 1\n\n'
3319 ... b'Done.\n'
3320 ... b'Test:\r\r'
3321 ... b' >>> x = 1 + 1\r\r'
3322 ... b'Done.\r'
3323 ... )
3324 95
3325 >>> with test_hook(dn):
3326 ... doctest.testfile("doctest_testfile.txt", package="doctest_testpkg", verbose=False)
3327 TestResults(failed=0, attempted=3)
3328 >>> shutil.rmtree(dn)
3329
3330 """
3331
3332 def test_testmod(): r"""
3333 Tests for the testmod function. More might be useful, but for now we're just
3334 testing the case raised by Issue 6195, where trying to doctest a C module would
3335 fail with a UnicodeDecodeError because doctest tried to read the "source" lines
3336 out of the binary module.
3337
3338 >>> import unicodedata
3339 >>> doctest.testmod(unicodedata, verbose=False)
3340 TestResults(failed=0, attempted=0)
3341 """
3342
3343 def test_testmod_errors(): r"""
3344 Tests for error reporting in the testmod() function.
3345
3346 >>> import test.test_doctest.sample_doctest_errors as mod
3347 >>> doctest.testmod(mod, verbose=False) # doctest: +ELLIPSIS
3348 **********************************************************************
3349 File "...sample_doctest_errors.py", line 5, in test.test_doctest.sample_doctest_errors
3350 Failed example:
3351 2 + 2
3352 Expected:
3353 5
3354 Got:
3355 4
3356 **********************************************************************
3357 File "...sample_doctest_errors.py", line 7, in test.test_doctest.sample_doctest_errors
3358 Failed example:
3359 1/0
3360 Exception raised:
3361 Traceback (most recent call last):
3362 File ...
3363 exec(compile(example.source, filename, "single",
3364 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3365 compileflags, True), test.globs)
3366 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3367 File "<doctest test.test_doctest.sample_doctest_errors[1]>", line 1, in <module>
3368 1/0
3369 ~^~
3370 ZeroDivisionError: division by zero
3371 **********************************************************************
3372 File "...sample_doctest_errors.py", line ?, in test.test_doctest.sample_doctest_errors.__test__.bad
3373 Failed example:
3374 2 + 2
3375 Expected:
3376 5
3377 Got:
3378 4
3379 **********************************************************************
3380 File "...sample_doctest_errors.py", line ?, in test.test_doctest.sample_doctest_errors.__test__.bad
3381 Failed example:
3382 1/0
3383 Exception raised:
3384 Traceback (most recent call last):
3385 File ...
3386 exec(compile(example.source, filename, "single",
3387 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3388 compileflags, True), test.globs)
3389 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3390 File "<doctest test.test_doctest.sample_doctest_errors.__test__.bad[1]>", line 1, in <module>
3391 1/0
3392 ~^~
3393 ZeroDivisionError: division by zero
3394 **********************************************************************
3395 File "...sample_doctest_errors.py", line 16, in test.test_doctest.sample_doctest_errors.errors
3396 Failed example:
3397 2 + 2
3398 Expected:
3399 5
3400 Got:
3401 4
3402 **********************************************************************
3403 File "...sample_doctest_errors.py", line 18, in test.test_doctest.sample_doctest_errors.errors
3404 Failed example:
3405 1/0
3406 Exception raised:
3407 Traceback (most recent call last):
3408 File ...
3409 exec(compile(example.source, filename, "single",
3410 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3411 compileflags, True), test.globs)
3412 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3413 File "<doctest test.test_doctest.sample_doctest_errors.errors[1]>", line 1, in <module>
3414 1/0
3415 ~^~
3416 ZeroDivisionError: division by zero
3417 **********************************************************************
3418 File "...sample_doctest_errors.py", line 23, in test.test_doctest.sample_doctest_errors.errors
3419 Failed example:
3420 f()
3421 Exception raised:
3422 Traceback (most recent call last):
3423 File ...
3424 exec(compile(example.source, filename, "single",
3425 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3426 compileflags, True), test.globs)
3427 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3428 File "<doctest test.test_doctest.sample_doctest_errors.errors[3]>", line 1, in <module>
3429 f()
3430 ~^^
3431 File "<doctest test.test_doctest.sample_doctest_errors.errors[2]>", line 2, in f
3432 2 + '2'
3433 ~~^~~~~
3434 TypeError: ...
3435 **********************************************************************
3436 File "...sample_doctest_errors.py", line 25, in test.test_doctest.sample_doctest_errors.errors
3437 Failed example:
3438 g()
3439 Exception raised:
3440 Traceback (most recent call last):
3441 File ...
3442 exec(compile(example.source, filename, "single",
3443 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3444 compileflags, True), test.globs)
3445 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3446 File "<doctest test.test_doctest.sample_doctest_errors.errors[4]>", line 1, in <module>
3447 g()
3448 ~^^
3449 File "...sample_doctest_errors.py", line 12, in g
3450 [][0] # line 12
3451 ~~^^^
3452 IndexError: list index out of range
3453 **********************************************************************
3454 File "...sample_doctest_errors.py", line 31, in test.test_doctest.sample_doctest_errors.syntax_error
3455 Failed example:
3456 2+*3
3457 Exception raised:
3458 Traceback (most recent call last):
3459 File ...
3460 exec(compile(example.source, filename, "single",
3461 ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3462 compileflags, True), test.globs)
3463 ^^^^^^^^^^^^^^^^^^^
3464 File "<doctest test.test_doctest.sample_doctest_errors.syntax_error[0]>", line 1
3465 2+*3
3466 ^
3467 SyntaxError: invalid syntax
3468 **********************************************************************
3469 4 items had failures:
3470 2 of 2 in test.test_doctest.sample_doctest_errors
3471 2 of 2 in test.test_doctest.sample_doctest_errors.__test__.bad
3472 4 of 5 in test.test_doctest.sample_doctest_errors.errors
3473 1 of 1 in test.test_doctest.sample_doctest_errors.syntax_error
3474 ***Test Failed*** 9 failures.
3475 TestResults(failed=9, attempted=10)
3476 """
3477
3478 try:
3479 os.fsencode("foo-bä[email protected]")
3480 supports_unicode = True
3481 except UnicodeEncodeError:
3482 # Skip the test: the filesystem encoding is unable to encode the filename
3483 supports_unicode = False
3484
3485 if supports_unicode:
3486 def test_unicode(): """
3487 Check doctest with a non-ascii filename:
3488
3489 >>> save_colorize = _colorize.COLORIZE
3490 >>> _colorize.COLORIZE = False
3491
3492 >>> doc = '''
3493 ... >>> raise Exception('clé')
3494 ... '''
3495 ...
3496 >>> parser = doctest.DocTestParser()
3497 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bä[email protected]", 0)
3498 >>> test
3499 <DocTest foo-bär@baz from foo-bä[email protected]:0 (1 example)>
3500 >>> runner = doctest.DocTestRunner(verbose=False)
3501 >>> runner.run(test) # doctest: +ELLIPSIS
3502 **********************************************************************
3503 File "foo-bä[email protected]", line 2, in foo-bär@baz
3504 Failed example:
3505 raise Exception('clé')
3506 Exception raised:
3507 Traceback (most recent call last):
3508 File ...
3509 exec(compile(example.source, filename, "single",
3510 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3511 compileflags, True), test.globs)
3512 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3513 File "<doctest foo-bär@baz[0]>", line 1, in <module>
3514 raise Exception('clé')
3515 Exception: clé
3516 TestResults(failed=1, attempted=1)
3517
3518 >>> _colorize.COLORIZE = save_colorize
3519 """
3520
3521
3522 @doctest_skip_if(not support.has_subprocess_support)
3523 def test_CLI(): r"""
3524 The doctest module can be used to run doctests against an arbitrary file.
3525 These tests test this CLI functionality.
3526
3527 We'll use the support module's script_helpers for this, and write a test files
3528 to a temp dir to run the command against. Due to a current limitation in
3529 script_helpers, though, we need a little utility function to turn the returned
3530 output into something we can doctest against:
3531
3532 >>> def normalize(s):
3533 ... return '\n'.join(s.decode().splitlines())
3534
3535 With those preliminaries out of the way, we'll start with a file with two
3536 simple tests and no errors. We'll run both the unadorned doctest command, and
3537 the verbose version, and then check the output:
3538
3539 >>> from test.support import script_helper
3540 >>> from test.support.os_helper import temp_dir
3541 >>> with temp_dir() as tmpdir:
3542 ... fn = os.path.join(tmpdir, 'myfile.doc')
3543 ... with open(fn, 'w', encoding='utf-8') as f:
3544 ... _ = f.write('This is a very simple test file.\n')
3545 ... _ = f.write(' >>> 1 + 1\n')
3546 ... _ = f.write(' 2\n')
3547 ... _ = f.write(' >>> "a"\n')
3548 ... _ = f.write(" 'a'\n")
3549 ... _ = f.write('\n')
3550 ... _ = f.write('And that is it.\n')
3551 ... rc1, out1, err1 = script_helper.assert_python_ok(
3552 ... '-m', 'doctest', fn)
3553 ... rc2, out2, err2 = script_helper.assert_python_ok(
3554 ... '-m', 'doctest', '-v', fn)
3555
3556 With no arguments and passing tests, we should get no output:
3557
3558 >>> rc1, out1, err1
3559 (0, b'', b'')
3560
3561 With the verbose flag, we should see the test output, but no error output:
3562
3563 >>> rc2, err2
3564 (0, b'')
3565 >>> print(normalize(out2))
3566 Trying:
3567 1 + 1
3568 Expecting:
3569 2
3570 ok
3571 Trying:
3572 "a"
3573 Expecting:
3574 'a'
3575 ok
3576 1 item passed all tests:
3577 2 tests in myfile.doc
3578 2 tests in 1 item.
3579 2 passed.
3580 Test passed.
3581
3582 Now we'll write a couple files, one with three tests, the other a python module
3583 with two tests, both of the files having "errors" in the tests that can be made
3584 non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
3585 the first file, NORMALIZE_WHITESPACE in the second). This combination will
3586 allow thoroughly testing the -f and -o flags, as well as the doctest command's
3587 ability to process more than one file on the command line and, since the second
3588 file ends in '.py', its handling of python module files (as opposed to straight
3589 text files).
3590
3591 >>> from test.support import script_helper
3592 >>> from test.support.os_helper import temp_dir
3593 >>> with temp_dir() as tmpdir:
3594 ... fn = os.path.join(tmpdir, 'myfile.doc')
3595 ... with open(fn, 'w', encoding="utf-8") as f:
3596 ... _ = f.write('This is another simple test file.\n')
3597 ... _ = f.write(' >>> 1 + 1\n')
3598 ... _ = f.write(' 2\n')
3599 ... _ = f.write(' >>> "abcdef"\n')
3600 ... _ = f.write(" 'a...f'\n")
3601 ... _ = f.write(' >>> "ajkml"\n')
3602 ... _ = f.write(" 'a...l'\n")
3603 ... _ = f.write('\n')
3604 ... _ = f.write('And that is it.\n')
3605 ... fn2 = os.path.join(tmpdir, 'myfile2.py')
3606 ... with open(fn2, 'w', encoding='utf-8') as f:
3607 ... _ = f.write('def test_func():\n')
3608 ... _ = f.write(' \"\"\"\n')
3609 ... _ = f.write(' This is simple python test function.\n')
3610 ... _ = f.write(' >>> 1 + 1\n')
3611 ... _ = f.write(' 2\n')
3612 ... _ = f.write(' >>> "abc def"\n')
3613 ... _ = f.write(" 'abc def'\n")
3614 ... _ = f.write("\n")
3615 ... _ = f.write(' \"\"\"\n')
3616 ... rc1, out1, err1 = script_helper.assert_python_failure(
3617 ... '-m', 'doctest', fn, fn2)
3618 ... rc2, out2, err2 = script_helper.assert_python_ok(
3619 ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
3620 ... rc3, out3, err3 = script_helper.assert_python_ok(
3621 ... '-m', 'doctest', '-o', 'ELLIPSIS',
3622 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
3623 ... rc4, out4, err4 = script_helper.assert_python_failure(
3624 ... '-m', 'doctest', '-f', fn, fn2)
3625 ... rc5, out5, err5 = script_helper.assert_python_ok(
3626 ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
3627 ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
3628
3629 Our first test run will show the errors from the first file (doctest stops if a
3630 file has errors). Note that doctest test-run error output appears on stdout,
3631 not stderr:
3632
3633 >>> rc1, err1
3634 (1, b'')
3635 >>> print(normalize(out1)) # doctest: +ELLIPSIS
3636 **********************************************************************
3637 File "...myfile.doc", line 4, in myfile.doc
3638 Failed example:
3639 "abcdef"
3640 Expected:
3641 'a...f'
3642 Got:
3643 'abcdef'
3644 **********************************************************************
3645 File "...myfile.doc", line 6, in myfile.doc
3646 Failed example:
3647 "ajkml"
3648 Expected:
3649 'a...l'
3650 Got:
3651 'ajkml'
3652 **********************************************************************
3653 1 item had failures:
3654 2 of 3 in myfile.doc
3655 ***Test Failed*** 2 failures.
3656
3657 With -o ELLIPSIS specified, the second run, against just the first file, should
3658 produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
3659 should the third, which ran against both files:
3660
3661 >>> rc2, out2, err2
3662 (0, b'', b'')
3663 >>> rc3, out3, err3
3664 (0, b'', b'')
3665
3666 The fourth run uses FAIL_FAST, so we should see only one error:
3667
3668 >>> rc4, err4
3669 (1, b'')
3670 >>> print(normalize(out4)) # doctest: +ELLIPSIS
3671 **********************************************************************
3672 File "...myfile.doc", line 4, in myfile.doc
3673 Failed example:
3674 "abcdef"
3675 Expected:
3676 'a...f'
3677 Got:
3678 'abcdef'
3679 **********************************************************************
3680 1 item had failures:
3681 1 of 2 in myfile.doc
3682 ***Test Failed*** 1 failure.
3683
3684 The fifth test uses verbose with the two options, so we should get verbose
3685 success output for the tests in both files:
3686
3687 >>> rc5, err5
3688 (0, b'')
3689 >>> print(normalize(out5))
3690 Trying:
3691 1 + 1
3692 Expecting:
3693 2
3694 ok
3695 Trying:
3696 "abcdef"
3697 Expecting:
3698 'a...f'
3699 ok
3700 Trying:
3701 "ajkml"
3702 Expecting:
3703 'a...l'
3704 ok
3705 1 item passed all tests:
3706 3 tests in myfile.doc
3707 3 tests in 1 item.
3708 3 passed.
3709 Test passed.
3710 Trying:
3711 1 + 1
3712 Expecting:
3713 2
3714 ok
3715 Trying:
3716 "abc def"
3717 Expecting:
3718 'abc def'
3719 ok
3720 1 item had no tests:
3721 myfile2
3722 1 item passed all tests:
3723 2 tests in myfile2.test_func
3724 2 tests in 2 items.
3725 2 passed.
3726 Test passed.
3727
3728 We should also check some typical error cases.
3729
3730 Invalid file name:
3731
3732 >>> rc, out, err = script_helper.assert_python_failure(
3733 ... '-m', 'doctest', 'nosuchfile')
3734 >>> rc, out
3735 (1, b'')
3736 >>> # The exact error message changes depending on the platform.
3737 >>> print(normalize(err)) # doctest: +ELLIPSIS
3738 Traceback (most recent call last):
3739 ...
3740 FileNotFoundError: [Errno ...] ...nosuchfile...
3741
3742 Invalid doctest option:
3743
3744 >>> rc, out, err = script_helper.assert_python_failure(
3745 ... '-m', 'doctest', '-o', 'nosuchoption')
3746 >>> rc, out
3747 (2, b'')
3748 >>> print(normalize(err)) # doctest: +ELLIPSIS
3749 usage...invalid...nosuchoption...
3750
3751 """
3752
3753 def test_no_trailing_whitespace_stripping():
3754 r"""
3755 The fancy reports had a bug for a long time where any trailing whitespace on
3756 the reported diff lines was stripped, making it impossible to see the
3757 differences in line reported as different that differed only in the amount of
3758 trailing whitespace. The whitespace still isn't particularly visible unless
3759 you use NDIFF, but at least it is now there to be found.
3760
3761 *NOTE*: This snippet was intentionally put inside a raw string to get rid of
3762 leading whitespace error in executing the example below
3763
3764 >>> def f(x):
3765 ... r'''
3766 ... >>> print('\n'.join(['a ', 'b']))
3767 ... a
3768 ... b
3769 ... '''
3770 """
3771 """
3772 *NOTE*: These doctest are not placed in raw string to depict the trailing whitespace
3773 using `\x20`
3774
3775 >>> test = doctest.DocTestFinder().find(f)[0]
3776 >>> flags = doctest.REPORT_NDIFF
3777 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
3778 ... # doctest: +ELLIPSIS
3779 **********************************************************************
3780 File ..., line 3, in f
3781 Failed example:
3782 print('\n'.join(['a ', 'b']))
3783 Differences (ndiff with -expected +actual):
3784 - a
3785 + a
3786 b
3787 TestResults(failed=1, attempted=1)
3788
3789 *NOTE*: `\x20` is for checking the trailing whitespace on the +a line above.
3790 We cannot use actual spaces there, as a commit hook prevents from committing
3791 patches that contain trailing whitespace. More info on Issue 24746.
3792 """
3793
3794
3795 def test_run_doctestsuite_multiple_times():
3796 """
3797 It was not possible to run the same DocTestSuite multiple times
3798 http://bugs.python.org/issue2604
3799 http://bugs.python.org/issue9736
3800
3801 >>> import unittest
3802 >>> import test.test_doctest.sample_doctest
3803 >>> suite = doctest.DocTestSuite(test.test_doctest.sample_doctest)
3804 >>> suite.run(unittest.TestResult())
3805 <unittest.result.TestResult run=9 errors=0 failures=4>
3806 >>> suite.run(unittest.TestResult())
3807 <unittest.result.TestResult run=9 errors=0 failures=4>
3808 """
3809
3810
3811 def test_exception_with_note(note):
3812 """
3813 >>> save_colorize = _colorize.COLORIZE
3814 >>> _colorize.COLORIZE = False
3815
3816 >>> test_exception_with_note('Note')
3817 Traceback (most recent call last):
3818 ...
3819 ValueError: Text
3820 Note
3821
3822 >>> test_exception_with_note('Note') # doctest: +IGNORE_EXCEPTION_DETAIL
3823 Traceback (most recent call last):
3824 ...
3825 ValueError: Text
3826 Note
3827
3828 >>> test_exception_with_note('''Note
3829 ... multiline
3830 ... example''')
3831 Traceback (most recent call last):
3832 ValueError: Text
3833 Note
3834 multiline
3835 example
3836
3837 Different note will fail the test:
3838
3839 >>> def f(x):
3840 ... r'''
3841 ... >>> exc = ValueError('message')
3842 ... >>> exc.add_note('note')
3843 ... >>> raise exc
3844 ... Traceback (most recent call last):
3845 ... ValueError: message
3846 ... wrong note
3847 ... '''
3848 >>> test = doctest.DocTestFinder().find(f)[0]
3849 >>> doctest.DocTestRunner(verbose=False).run(test)
3850 ... # doctest: +ELLIPSIS
3851 **********************************************************************
3852 File "...", line 5, in f
3853 Failed example:
3854 raise exc
3855 Expected:
3856 Traceback (most recent call last):
3857 ValueError: message
3858 wrong note
3859 Got:
3860 Traceback (most recent call last):
3861 ...
3862 ValueError: message
3863 note
3864 TestResults(failed=1, attempted=...)
3865
3866 >>> _colorize.COLORIZE = save_colorize
3867 """
3868 exc = ValueError('Text')
3869 exc.add_note(note)
3870 raise exc
3871
3872
3873 def test_exception_with_multiple_notes():
3874 """
3875 >>> test_exception_with_multiple_notes()
3876 Traceback (most recent call last):
3877 ...
3878 ValueError: Text
3879 One
3880 Two
3881 """
3882 exc = ValueError('Text')
3883 exc.add_note('One')
3884 exc.add_note('Two')
3885 raise exc
3886
3887
3888 def test_syntax_error_with_note(cls, multiline=False):
3889 """
3890 >>> test_syntax_error_with_note(SyntaxError)
3891 Traceback (most recent call last):
3892 ...
3893 SyntaxError: error
3894 Note
3895
3896 >>> test_syntax_error_with_note(SyntaxError)
3897 Traceback (most recent call last):
3898 SyntaxError: error
3899 Note
3900
3901 >>> test_syntax_error_with_note(SyntaxError)
3902 Traceback (most recent call last):
3903 ...
3904 File "x.py", line 23
3905 bad syntax
3906 SyntaxError: error
3907 Note
3908
3909 >>> test_syntax_error_with_note(IndentationError)
3910 Traceback (most recent call last):
3911 ...
3912 IndentationError: error
3913 Note
3914
3915 >>> test_syntax_error_with_note(TabError, multiline=True)
3916 Traceback (most recent call last):
3917 ...
3918 TabError: error
3919 Note
3920 Line
3921 """
3922 exc = cls("error", ("x.py", 23, None, "bad syntax"))
3923 exc.add_note('Note\nLine' if multiline else 'Note')
3924 raise exc
3925
3926
3927 def test_syntax_error_subclass_from_stdlib():
3928 """
3929 `ParseError` is a subclass of `SyntaxError`, but it is not a builtin:
3930
3931 >>> test_syntax_error_subclass_from_stdlib()
3932 Traceback (most recent call last):
3933 ...
3934 xml.etree.ElementTree.ParseError: error
3935 error
3936 Note
3937 Line
3938 """
3939 from xml.etree.ElementTree import ParseError
3940 exc = ParseError("error\nerror")
3941 exc.add_note('Note\nLine')
3942 raise exc
3943
3944
3945 def test_syntax_error_with_incorrect_expected_note():
3946 """
3947 >>> save_colorize = _colorize.COLORIZE
3948 >>> _colorize.COLORIZE = False
3949
3950 >>> def f(x):
3951 ... r'''
3952 ... >>> exc = SyntaxError("error", ("x.py", 23, None, "bad syntax"))
3953 ... >>> exc.add_note('note1')
3954 ... >>> exc.add_note('note2')
3955 ... >>> raise exc
3956 ... Traceback (most recent call last):
3957 ... SyntaxError: error
3958 ... wrong note
3959 ... '''
3960 >>> test = doctest.DocTestFinder().find(f)[0]
3961 >>> doctest.DocTestRunner(verbose=False).run(test)
3962 ... # doctest: +ELLIPSIS
3963 **********************************************************************
3964 File "...", line 6, in f
3965 Failed example:
3966 raise exc
3967 Expected:
3968 Traceback (most recent call last):
3969 SyntaxError: error
3970 wrong note
3971 Got:
3972 Traceback (most recent call last):
3973 ...
3974 SyntaxError: error
3975 note1
3976 note2
3977 TestResults(failed=1, attempted=...)
3978
3979 >>> _colorize.COLORIZE = save_colorize
3980 """
3981
3982
3983 def load_tests(loader, tests, pattern):
3984 tests.addTest(doctest.DocTestSuite(doctest))
3985 tests.addTest(doctest.DocTestSuite())
3986 return tests
3987
3988
3989 if __name__ == '__main__':
3990 unittest.main(module='test.test_doctest.test_doctest')