Debian Codegraph @

lib-python/3/test/test_doctest/test_doctest.py

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