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