1:mod:`test` --- Regression tests package for Python 2=================================================== 3 4.. module:: test 5 :synopsis: Regression tests package containing the testing suite for Python. 6 7.. sectionauthor:: Brett Cannon <brett@python.org> 8 9.. note:: 10 The :mod:`test` package is meant for internal use by Python only. It is 11 documented for the benefit of the core developers of Python. Any use of 12 this package outside of Python's standard library is discouraged as code 13 mentioned here can change or be removed without notice between releases of 14 Python. 15 16-------------- 17 18The :mod:`test` package contains all regression tests for Python as well as the 19modules :mod:`test.support` and :mod:`test.regrtest`. 20:mod:`test.support` is used to enhance your tests while 21:mod:`test.regrtest` drives the testing suite. 22 23Each module in the :mod:`test` package whose name starts with ``test_`` is a 24testing suite for a specific module or feature. All new tests should be written 25using the :mod:`unittest` or :mod:`doctest` module. Some older tests are 26written using a "traditional" testing style that compares output printed to 27``sys.stdout``; this style of test is considered deprecated. 28 29 30.. seealso:: 31 32 Module :mod:`unittest` 33 Writing PyUnit regression tests. 34 35 Module :mod:`doctest` 36 Tests embedded in documentation strings. 37 38 39.. _writing-tests: 40 41Writing Unit Tests for the :mod:`test` package 42---------------------------------------------- 43 44It is preferred that tests that use the :mod:`unittest` module follow a few 45guidelines. One is to name the test module by starting it with ``test_`` and end 46it with the name of the module being tested. The test methods in the test module 47should start with ``test_`` and end with a description of what the method is 48testing. This is needed so that the methods are recognized by the test driver as 49test methods. Also, no documentation string for the method should be included. A 50comment (such as ``# Tests function returns only True or False``) should be used 51to provide documentation for test methods. This is done because documentation 52strings get printed out if they exist and thus what test is being run is not 53stated. 54 55A basic boilerplate is often used:: 56 57 import unittest 58 from test import support 59 60 class MyTestCase1(unittest.TestCase): 61 62 # Only use setUp() and tearDown() if necessary 63 64 def setUp(self): 65 ... code to execute in preparation for tests ... 66 67 def tearDown(self): 68 ... code to execute to clean up after tests ... 69 70 def test_feature_one(self): 71 # Test feature one. 72 ... testing code ... 73 74 def test_feature_two(self): 75 # Test feature two. 76 ... testing code ... 77 78 ... more test methods ... 79 80 class MyTestCase2(unittest.TestCase): 81 ... same structure as MyTestCase1 ... 82 83 ... more test classes ... 84 85 if __name__ == '__main__': 86 unittest.main() 87 88This code pattern allows the testing suite to be run by :mod:`test.regrtest`, 89on its own as a script that supports the :mod:`unittest` CLI, or via the 90``python -m unittest`` CLI. 91 92The goal for regression testing is to try to break code. This leads to a few 93guidelines to be followed: 94 95* The testing suite should exercise all classes, functions, and constants. This 96 includes not just the external API that is to be presented to the outside 97 world but also "private" code. 98 99* Whitebox testing (examining the code being tested when the tests are being 100 written) is preferred. Blackbox testing (testing only the published user 101 interface) is not complete enough to make sure all boundary and edge cases 102 are tested. 103 104* Make sure all possible values are tested including invalid ones. This makes 105 sure that not only all valid values are acceptable but also that improper 106 values are handled correctly. 107 108* Exhaust as many code paths as possible. Test where branching occurs and thus 109 tailor input to make sure as many different paths through the code are taken. 110 111* Add an explicit test for any bugs discovered for the tested code. This will 112 make sure that the error does not crop up again if the code is changed in the 113 future. 114 115* Make sure to clean up after your tests (such as close and remove all temporary 116 files). 117 118* If a test is dependent on a specific condition of the operating system then 119 verify the condition already exists before attempting the test. 120 121* Import as few modules as possible and do it as soon as possible. This 122 minimizes external dependencies of tests and also minimizes possible anomalous 123 behavior from side-effects of importing a module. 124 125* Try to maximize code reuse. On occasion, tests will vary by something as small 126 as what type of input is used. Minimize code duplication by subclassing a 127 basic test class with a class that specifies the input:: 128 129 class TestFuncAcceptsSequencesMixin: 130 131 func = mySuperWhammyFunction 132 133 def test_func(self): 134 self.func(self.arg) 135 136 class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase): 137 arg = [1, 2, 3] 138 139 class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase): 140 arg = 'abc' 141 142 class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase): 143 arg = (1, 2, 3) 144 145 When using this pattern, remember that all classes that inherit from 146 :class:`unittest.TestCase` are run as tests. The :class:`Mixin` class in the example above 147 does not have any data and so can't be run by itself, thus it does not 148 inherit from :class:`unittest.TestCase`. 149 150 151.. seealso:: 152 153 Test Driven Development 154 A book by Kent Beck on writing tests before code. 155 156 157.. _regrtest: 158 159Running tests using the command-line interface 160---------------------------------------------- 161 162The :mod:`test` package can be run as a script to drive Python's regression 163test suite, thanks to the :option:`-m` option: :program:`python -m test`. Under 164the hood, it uses :mod:`test.regrtest`; the call :program:`python -m 165test.regrtest` used in previous Python versions still works. Running the 166script by itself automatically starts running all regression tests in the 167:mod:`test` package. It does this by finding all modules in the package whose 168name starts with ``test_``, importing them, and executing the function 169:func:`test_main` if present or loading the tests via 170unittest.TestLoader.loadTestsFromModule if ``test_main`` does not exist. The 171names of tests to execute may also be passed to the script. Specifying a single 172regression test (:program:`python -m test test_spam`) will minimize output and 173only print whether the test passed or failed. 174 175Running :mod:`test` directly allows what resources are available for 176tests to use to be set. You do this by using the ``-u`` command-line 177option. Specifying ``all`` as the value for the ``-u`` option enables all 178possible resources: :program:`python -m test -uall`. 179If all but one resource is desired (a more common case), a 180comma-separated list of resources that are not desired may be listed after 181``all``. The command :program:`python -m test -uall,-audio,-largefile` 182will run :mod:`test` with all resources except the ``audio`` and 183``largefile`` resources. For a list of all resources and more command-line 184options, run :program:`python -m test -h`. 185 186Some other ways to execute the regression tests depend on what platform the 187tests are being executed on. On Unix, you can run :program:`make test` at the 188top-level directory where Python was built. On Windows, 189executing :program:`rt.bat` from your :file:`PCbuild` directory will run all 190regression tests. 191 192 193:mod:`test.support` --- Utilities for the Python test suite 194=========================================================== 195 196.. module:: test.support 197 :synopsis: Support for Python's regression test suite. 198 199 200The :mod:`test.support` module provides support for Python's regression 201test suite. 202 203.. note:: 204 205 :mod:`test.support` is not a public module. It is documented here to help 206 Python developers write tests. The API of this module is subject to change 207 without backwards compatibility concerns between releases. 208 209 210This module defines the following exceptions: 211 212.. exception:: TestFailed 213 214 Exception to be raised when a test fails. This is deprecated in favor of 215 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion 216 methods. 217 218 219.. exception:: ResourceDenied 220 221 Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a 222 network connection) is not available. Raised by the :func:`requires` 223 function. 224 225 226The :mod:`test.support` module defines the following constants: 227 228.. data:: verbose 229 230 ``True`` when verbose output is enabled. Should be checked when more 231 detailed information is desired about a running test. *verbose* is set by 232 :mod:`test.regrtest`. 233 234 235.. data:: is_jython 236 237 ``True`` if the running interpreter is Jython. 238 239 240.. data:: is_android 241 242 ``True`` if the system is Android. 243 244 245.. data:: unix_shell 246 247 Path for shell if not on Windows; otherwise ``None``. 248 249 250.. data:: FS_NONASCII 251 252 A non-ASCII character encodable by :func:`os.fsencode`. 253 254 255.. data:: TESTFN 256 257 Set to a name that is safe to use as the name of a temporary file. Any 258 temporary file that is created should be closed and unlinked (removed). 259 260 261.. data:: TESTFN_UNICODE 262 263 Set to a non-ASCII name for a temporary file. 264 265 266.. data:: TESTFN_ENCODING 267 268 Set to :func:`sys.getfilesystemencoding`. 269 270 271.. data:: TESTFN_UNENCODABLE 272 273 Set to a filename (str type) that should not be able to be encoded by file 274 system encoding in strict mode. It may be ``None`` if it's not possible to 275 generate such a filename. 276 277 278.. data:: TESTFN_UNDECODABLE 279 280 Set to a filename (bytes type) that should not be able to be decoded by 281 file system encoding in strict mode. It may be ``None`` if it's not 282 possible to generate such a filename. 283 284 285.. data:: TESTFN_NONASCII 286 287 Set to a filename containing the :data:`FS_NONASCII` character. 288 289 290.. data:: IPV6_ENABLED 291 292 Set to ``True`` if IPV6 is enabled on this host, ``False`` otherwise. 293 294 295.. data:: SAVEDCWD 296 297 Set to :func:`os.getcwd`. 298 299 300.. data:: PGO 301 302 Set when tests can be skipped when they are not useful for PGO. 303 304 305.. data:: PIPE_MAX_SIZE 306 307 A constant that is likely larger than the underlying OS pipe buffer size, 308 to make writes blocking. 309 310 311.. data:: SOCK_MAX_SIZE 312 313 A constant that is likely larger than the underlying OS socket buffer size, 314 to make writes blocking. 315 316 317.. data:: TEST_SUPPORT_DIR 318 319 Set to the top level directory that contains :mod:`test.support`. 320 321 322.. data:: TEST_HOME_DIR 323 324 Set to the top level directory for the test package. 325 326 327.. data:: TEST_DATA_DIR 328 329 Set to the ``data`` directory within the test package. 330 331 332.. data:: MAX_Py_ssize_t 333 334 Set to :data:`sys.maxsize` for big memory tests. 335 336 337.. data:: max_memuse 338 339 Set by :func:`set_memlimit` as the memory limit for big memory tests. 340 Limited by :data:`MAX_Py_ssize_t`. 341 342 343.. data:: real_max_memuse 344 345 Set by :func:`set_memlimit` as the memory limit for big memory tests. Not 346 limited by :data:`MAX_Py_ssize_t`. 347 348 349.. data:: MISSING_C_DOCSTRINGS 350 351 Return ``True`` if running on CPython, not on Windows, and configuration 352 not set with ``WITH_DOC_STRINGS``. 353 354 355.. data:: HAVE_DOCSTRINGS 356 357 Check for presence of docstrings. 358 359 360.. data:: TEST_HTTP_URL 361 362 Define the URL of a dedicated HTTP server for the network tests. 363 364 365.. data:: ALWAYS_EQ 366 367 Object that is equal to anything. Used to test mixed type comparison. 368 369 370.. data:: LARGEST 371 372 Object that is greater than anything (except itself). 373 Used to test mixed type comparison. 374 375 376.. data:: SMALLEST 377 378 Object that is less than anything (except itself). 379 Used to test mixed type comparison. 380 381 382The :mod:`test.support` module defines the following functions: 383 384.. function:: forget(module_name) 385 386 Remove the module named *module_name* from ``sys.modules`` and delete any 387 byte-compiled files of the module. 388 389 390.. function:: unload(name) 391 392 Delete *name* from ``sys.modules``. 393 394 395.. function:: unlink(filename) 396 397 Call :func:`os.unlink` on *filename*. On Windows platforms, this is 398 wrapped with a wait loop that checks for the existence fo the file. 399 400 401.. function:: rmdir(filename) 402 403 Call :func:`os.rmdir` on *filename*. On Windows platforms, this is 404 wrapped with a wait loop that checks for the existence of the file. 405 406 407.. function:: rmtree(path) 408 409 Call :func:`shutil.rmtree` on *path* or call :func:`os.lstat` and 410 :func:`os.rmdir` to remove a path and its contents. On Windows platforms, 411 this is wrapped with a wait loop that checks for the existence of the files. 412 413 414.. function:: make_legacy_pyc(source) 415 416 Move a :pep:`3147`/:pep:`488` pyc file to its legacy pyc location and return the file 417 system path to the legacy pyc file. The *source* value is the file system 418 path to the source file. It does not need to exist, however the PEP 419 3147/488 pyc file must exist. 420 421 422.. function:: is_resource_enabled(resource) 423 424 Return ``True`` if *resource* is enabled and available. The list of 425 available resources is only set when :mod:`test.regrtest` is executing the 426 tests. 427 428 429.. function:: python_is_optimized() 430 431 Return ``True`` if Python was not built with ``-O0`` or ``-Og``. 432 433 434.. function:: with_pymalloc() 435 436 Return :data:`_testcapi.WITH_PYMALLOC`. 437 438 439.. function:: requires(resource, msg=None) 440 441 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the 442 argument to :exc:`ResourceDenied` if it is raised. Always returns 443 ``True`` if called by a function whose ``__name__`` is ``'__main__'``. 444 Used when tests are executed by :mod:`test.regrtest`. 445 446 447.. function:: system_must_validate_cert(f) 448 449 Raise :exc:`unittest.SkipTest` on TLS certification validation failures. 450 451 452.. function:: sortdict(dict) 453 454 Return a repr of *dict* with keys sorted. 455 456 457.. function:: findfile(filename, subdir=None) 458 459 Return the path to the file named *filename*. If no match is found 460 *filename* is returned. This does not equal a failure since it could be the 461 path to the file. 462 463 Setting *subdir* indicates a relative path to use to find the file 464 rather than looking directly in the path directories. 465 466 467.. function:: create_empty_file(filename) 468 469 Create an empty file with *filename*. If it already exists, truncate it. 470 471 472.. function:: fd_count() 473 474 Count the number of open file descriptors. 475 476 477.. function:: match_test(test) 478 479 Match *test* to patterns set in :func:`set_match_tests`. 480 481 482.. function:: set_match_tests(patterns) 483 484 Define match test with regular expression *patterns*. 485 486 487.. function:: run_unittest(\*classes) 488 489 Execute :class:`unittest.TestCase` subclasses passed to the function. The 490 function scans the classes for methods starting with the prefix ``test_`` 491 and executes the tests individually. 492 493 It is also legal to pass strings as parameters; these should be keys in 494 ``sys.modules``. Each associated module will be scanned by 495 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the 496 following :func:`test_main` function:: 497 498 def test_main(): 499 support.run_unittest(__name__) 500 501 This will run all tests defined in the named module. 502 503 504.. function:: run_doctest(module, verbosity=None, optionflags=0) 505 506 Run :func:`doctest.testmod` on the given *module*. Return 507 ``(failure_count, test_count)``. 508 509 If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity 510 set to :data:`verbose`. Otherwise, it is run with verbosity set to 511 ``None``. *optionflags* is passed as ``optionflags`` to 512 :func:`doctest.testmod`. 513 514 515.. function:: setswitchinterval(interval) 516 517 Set the :func:`sys.setswitchinterval` to the given *interval*. Defines 518 a minimum interval for Android systems to prevent the system from hanging. 519 520 521.. function:: check_impl_detail(**guards) 522 523 Use this check to guard CPython's implementation-specific tests or to 524 run them only on the implementations guarded by the arguments:: 525 526 check_impl_detail() # Only on CPython (default). 527 check_impl_detail(jython=True) # Only on Jython. 528 check_impl_detail(cpython=False) # Everywhere except CPython. 529 530 531.. function:: check_warnings(\*filters, quiet=True) 532 533 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it 534 easier to test that a warning was correctly raised. It is approximately 535 equivalent to calling ``warnings.catch_warnings(record=True)`` with 536 :meth:`warnings.simplefilter` set to ``always`` and with the option to 537 automatically validate the results that are recorded. 538 539 ``check_warnings`` accepts 2-tuples of the form ``("message regexp", 540 WarningCategory)`` as positional arguments. If one or more *filters* are 541 provided, or if the optional keyword argument *quiet* is ``False``, 542 it checks to make sure the warnings are as expected: each specified filter 543 must match at least one of the warnings raised by the enclosed code or the 544 test fails, and if any warnings are raised that do not match any of the 545 specified filters the test fails. To disable the first of these checks, 546 set *quiet* to ``True``. 547 548 If no arguments are specified, it defaults to:: 549 550 check_warnings(("", Warning), quiet=True) 551 552 In this case all warnings are caught and no errors are raised. 553 554 On entry to the context manager, a :class:`WarningRecorder` instance is 555 returned. The underlying warnings list from 556 :func:`~warnings.catch_warnings` is available via the recorder object's 557 :attr:`warnings` attribute. As a convenience, the attributes of the object 558 representing the most recent warning can also be accessed directly through 559 the recorder object (see example below). If no warning has been raised, 560 then any of the attributes that would otherwise be expected on an object 561 representing a warning will return ``None``. 562 563 The recorder object also has a :meth:`reset` method, which clears the 564 warnings list. 565 566 The context manager is designed to be used like this:: 567 568 with check_warnings(("assertion is always true", SyntaxWarning), 569 ("", UserWarning)): 570 exec('assert(False, "Hey!")') 571 warnings.warn(UserWarning("Hide me!")) 572 573 In this case if either warning was not raised, or some other warning was 574 raised, :func:`check_warnings` would raise an error. 575 576 When a test needs to look more deeply into the warnings, rather than 577 just checking whether or not they occurred, code like this can be used:: 578 579 with check_warnings(quiet=True) as w: 580 warnings.warn("foo") 581 assert str(w.args[0]) == "foo" 582 warnings.warn("bar") 583 assert str(w.args[0]) == "bar" 584 assert str(w.warnings[0].args[0]) == "foo" 585 assert str(w.warnings[1].args[0]) == "bar" 586 w.reset() 587 assert len(w.warnings) == 0 588 589 590 Here all warnings will be caught, and the test code tests the captured 591 warnings directly. 592 593 .. versionchanged:: 3.2 594 New optional arguments *filters* and *quiet*. 595 596 597.. function:: check_no_resource_warning(testcase) 598 599 Context manager to check that no :exc:`ResourceWarning` was raised. You 600 must remove the object which may emit :exc:`ResourceWarning` before the 601 end of the context manager. 602 603 604.. function:: set_memlimit(limit) 605 606 Set the values for :data:`max_memuse` and :data:`real_max_memuse` for big 607 memory tests. 608 609 610.. function:: record_original_stdout(stdout) 611 612 Store the value from *stdout*. It is meant to hold the stdout at the 613 time the regrtest began. 614 615 616.. function:: get_original_stdout 617 618 Return the original stdout set by :func:`record_original_stdout` or 619 ``sys.stdout`` if it's not set. 620 621 622.. function:: strip_python_strerr(stderr) 623 624 Strip the *stderr* of a Python process from potential debug output 625 emitted by the interpreter. This will typically be run on the result of 626 :meth:`subprocess.Popen.communicate`. 627 628 629.. function:: args_from_interpreter_flags() 630 631 Return a list of command line arguments reproducing the current settings 632 in ``sys.flags`` and ``sys.warnoptions``. 633 634 635.. function:: optim_args_from_interpreter_flags() 636 637 Return a list of command line arguments reproducing the current 638 optimization settings in ``sys.flags``. 639 640 641.. function:: captured_stdin() 642 captured_stdout() 643 captured_stderr() 644 645 A context managers that temporarily replaces the named stream with 646 :class:`io.StringIO` object. 647 648 Example use with output streams:: 649 650 with captured_stdout() as stdout, captured_stderr() as stderr: 651 print("hello") 652 print("error", file=sys.stderr) 653 assert stdout.getvalue() == "hello\n" 654 assert stderr.getvalue() == "error\n" 655 656 Example use with input stream:: 657 658 with captured_stdin() as stdin: 659 stdin.write('hello\n') 660 stdin.seek(0) 661 # call test code that consumes from sys.stdin 662 captured = input() 663 self.assertEqual(captured, "hello") 664 665 666.. function:: temp_dir(path=None, quiet=False) 667 668 A context manager that creates a temporary directory at *path* and 669 yields the directory. 670 671 If *path* is ``None``, the temporary directory is created using 672 :func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager 673 raises an exception on error. Otherwise, if *path* is specified and 674 cannot be created, only a warning is issued. 675 676 677.. function:: change_cwd(path, quiet=False) 678 679 A context manager that temporarily changes the current working 680 directory to *path* and yields the directory. 681 682 If *quiet* is ``False``, the context manager raises an exception 683 on error. Otherwise, it issues only a warning and keeps the current 684 working directory the same. 685 686 687.. function:: temp_cwd(name='tempcwd', quiet=False) 688 689 A context manager that temporarily creates a new directory and 690 changes the current working directory (CWD). 691 692 The context manager creates a temporary directory in the current 693 directory with name *name* before temporarily changing the current 694 working directory. If *name* is ``None``, the temporary directory is 695 created using :func:`tempfile.mkdtemp`. 696 697 If *quiet* is ``False`` and it is not possible to create or change 698 the CWD, an error is raised. Otherwise, only a warning is raised 699 and the original CWD is used. 700 701 702.. function:: temp_umask(umask) 703 704 A context manager that temporarily sets the process umask. 705 706 707.. function:: transient_internet(resource_name, *, timeout=30.0, errnos=()) 708 709 A context manager that raises :exc:`ResourceDenied` when various issues 710 with the internet connection manifest themselves as exceptions. 711 712 713.. function:: disable_faulthandler() 714 715 A context manager that replaces ``sys.stderr`` with ``sys.__stderr__``. 716 717 718.. function:: gc_collect() 719 720 Force as many objects as possible to be collected. This is needed because 721 timely deallocation is not guaranteed by the garbage collector. This means 722 that ``__del__`` methods may be called later than expected and weakrefs 723 may remain alive for longer than expected. 724 725 726.. function:: disable_gc() 727 728 A context manager that disables the garbage collector upon entry and 729 reenables it upon exit. 730 731 732.. function:: swap_attr(obj, attr, new_val) 733 734 Context manager to swap out an attribute with a new object. 735 736 Usage:: 737 738 with swap_attr(obj, "attr", 5): 739 ... 740 741 This will set ``obj.attr`` to 5 for the duration of the ``with`` block, 742 restoring the old value at the end of the block. If ``attr`` doesn't 743 exist on ``obj``, it will be created and then deleted at the end of the 744 block. 745 746 The old value (or ``None`` if it doesn't exist) will be assigned to the 747 target of the "as" clause, if there is one. 748 749 750.. function:: swap_item(obj, attr, new_val) 751 752 Context manager to swap out an item with a new object. 753 754 Usage:: 755 756 with swap_item(obj, "item", 5): 757 ... 758 759 This will set ``obj["item"]`` to 5 for the duration of the ``with`` block, 760 restoring the old value at the end of the block. If ``item`` doesn't 761 exist on ``obj``, it will be created and then deleted at the end of the 762 block. 763 764 The old value (or ``None`` if it doesn't exist) will be assigned to the 765 target of the "as" clause, if there is one. 766 767 768.. function:: wait_threads_exit(timeout=60.0) 769 770 Context manager to wait until all threads created in the ``with`` statement 771 exit. 772 773 774.. function:: start_threads(threads, unlock=None) 775 776 Context manager to start *threads*. It attempts to join the threads upon 777 exit. 778 779 780.. function:: calcobjsize(fmt) 781 782 Return :func:`struct.calcsize` for ``nP{fmt}0n`` or, if ``gettotalrefcount`` 783 exists, ``2PnP{fmt}0P``. 784 785 786.. function:: calcvobjsize(fmt) 787 788 Return :func:`struct.calcsize` for ``nPn{fmt}0n`` or, if ``gettotalrefcount`` 789 exists, ``2PnPn{fmt}0P``. 790 791 792.. function:: checksizeof(test, o, size) 793 794 For testcase *test*, assert that the ``sys.getsizeof`` for *o* plus the GC 795 header size equals *size*. 796 797 798.. function:: can_symlink() 799 800 Return ``True`` if the OS supports symbolic links, ``False`` 801 otherwise. 802 803 804.. function:: can_xattr() 805 806 Return ``True`` if the OS supports xattr, ``False`` 807 otherwise. 808 809 810.. decorator:: skip_unless_symlink 811 812 A decorator for running tests that require support for symbolic links. 813 814 815.. decorator:: skip_unless_xattr 816 817 A decorator for running tests that require support for xattr. 818 819 820.. decorator:: skip_unless_bind_unix_socket 821 822 A decorator for running tests that require a functional bind() for Unix 823 sockets. 824 825 826.. decorator:: anticipate_failure(condition) 827 828 A decorator to conditionally mark tests with 829 :func:`unittest.expectedFailure`. Any use of this decorator should 830 have an associated comment identifying the relevant tracker issue. 831 832 833.. decorator:: run_with_locale(catstr, *locales) 834 835 A decorator for running a function in a different locale, correctly 836 resetting it after it has finished. *catstr* is the locale category as 837 a string (for example ``"LC_ALL"``). The *locales* passed will be tried 838 sequentially, and the first valid locale will be used. 839 840 841.. decorator:: run_with_tz(tz) 842 843 A decorator for running a function in a specific timezone, correctly 844 resetting it after it has finished. 845 846 847.. decorator:: requires_freebsd_version(*min_version) 848 849 Decorator for the minimum version when running test on FreeBSD. If the 850 FreeBSD version is less than the minimum, raise :exc:`unittest.SkipTest`. 851 852 853.. decorator:: requires_linux_version(*min_version) 854 855 Decorator for the minimum version when running test on Linux. If the 856 Linux version is less than the minimum, raise :exc:`unittest.SkipTest`. 857 858 859.. decorator:: requires_mac_version(*min_version) 860 861 Decorator for the minimum version when running test on Mac OS X. If the 862 MAC OS X version is less than the minimum, raise :exc:`unittest.SkipTest`. 863 864 865.. decorator:: requires_IEEE_754 866 867 Decorator for skipping tests on non-IEEE 754 platforms. 868 869 870.. decorator:: requires_zlib 871 872 Decorator for skipping tests if :mod:`zlib` doesn't exist. 873 874 875.. decorator:: requires_gzip 876 877 Decorator for skipping tests if :mod:`gzip` doesn't exist. 878 879 880.. decorator:: requires_bz2 881 882 Decorator for skipping tests if :mod:`bz2` doesn't exist. 883 884 885.. decorator:: requires_lzma 886 887 Decorator for skipping tests if :mod:`lzma` doesn't exist. 888 889 890.. decorator:: requires_resource(resource) 891 892 Decorator for skipping tests if *resource* is not available. 893 894 895.. decorator:: requires_docstrings 896 897 Decorator for only running the test if :data:`HAVE_DOCSTRINGS`. 898 899 900.. decorator:: cpython_only(test) 901 902 Decorator for tests only applicable to CPython. 903 904 905.. decorator:: impl_detail(msg=None, **guards) 906 907 Decorator for invoking :func:`check_impl_detail` on *guards*. If that 908 returns ``False``, then uses *msg* as the reason for skipping the test. 909 910 911.. decorator:: no_tracing(func) 912 913 Decorator to temporarily turn off tracing for the duration of the test. 914 915 916.. decorator:: refcount_test(test) 917 918 Decorator for tests which involve reference counting. The decorator does 919 not run the test if it is not run by CPython. Any trace function is unset 920 for the duration of the test to prevent unexpected refcounts caused by 921 the trace function. 922 923 924.. decorator:: reap_threads(func) 925 926 Decorator to ensure the threads are cleaned up even if the test fails. 927 928 929.. decorator:: bigmemtest(size, memuse, dry_run=True) 930 931 Decorator for bigmem tests. 932 933 *size* is a requested size for the test (in arbitrary, test-interpreted 934 units.) *memuse* is the number of bytes per unit for the test, or a good 935 estimate of it. For example, a test that needs two byte buffers, of 4 GiB 936 each, could be decorated with ``@bigmemtest(size=_4G, memuse=2)``. 937 938 The *size* argument is normally passed to the decorated test method as an 939 extra argument. If *dry_run* is ``True``, the value passed to the test 940 method may be less than the requested value. If *dry_run* is ``False``, it 941 means the test doesn't support dummy runs when ``-M`` is not specified. 942 943 944.. decorator:: bigaddrspacetest(f) 945 946 Decorator for tests that fill the address space. *f* is the function to 947 wrap. 948 949 950.. function:: make_bad_fd() 951 952 Create an invalid file descriptor by opening and closing a temporary file, 953 and returning its descriptor. 954 955 956.. function:: check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None) 957 958 Test for syntax errors in *statement* by attempting to compile *statement*. 959 *testcase* is the :mod:`unittest` instance for the test. *errtext* is the 960 regular expression which should match the string representation of the 961 raised :exc:`SyntaxError`. If *lineno* is not ``None``, compares to 962 the line of the exception. If *offset* is not ``None``, compares to 963 the offset of the exception. 964 965 966.. function:: check_syntax_warning(testcase, statement, errtext='', *, lineno=1, offset=None) 967 968 Test for syntax warning in *statement* by attempting to compile *statement*. 969 Test also that the :exc:`SyntaxWarning` is emitted only once, and that it 970 will be converted to a :exc:`SyntaxError` when turned into error. 971 *testcase* is the :mod:`unittest` instance for the test. *errtext* is the 972 regular expression which should match the string representation of the 973 emitted :exc:`SyntaxWarning` and raised :exc:`SyntaxError`. If *lineno* 974 is not ``None``, compares to the line of the warning and exception. 975 If *offset* is not ``None``, compares to the offset of the exception. 976 977 .. versionadded:: 3.8 978 979 980.. function:: open_urlresource(url, *args, **kw) 981 982 Open *url*. If open fails, raises :exc:`TestFailed`. 983 984 985.. function:: import_module(name, deprecated=False, *, required_on()) 986 987 This function imports and returns the named module. Unlike a normal 988 import, this function raises :exc:`unittest.SkipTest` if the module 989 cannot be imported. 990 991 Module and package deprecation messages are suppressed during this import 992 if *deprecated* is ``True``. If a module is required on a platform but 993 optional for others, set *required_on* to an iterable of platform prefixes 994 which will be compared against :data:`sys.platform`. 995 996 .. versionadded:: 3.1 997 998 999.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False) 1000 1001 This function imports and returns a fresh copy of the named Python module 1002 by removing the named module from ``sys.modules`` before doing the import. 1003 Note that unlike :func:`reload`, the original module is not affected by 1004 this operation. 1005 1006 *fresh* is an iterable of additional module names that are also removed 1007 from the ``sys.modules`` cache before doing the import. 1008 1009 *blocked* is an iterable of module names that are replaced with ``None`` 1010 in the module cache during the import to ensure that attempts to import 1011 them raise :exc:`ImportError`. 1012 1013 The named module and any modules named in the *fresh* and *blocked* 1014 parameters are saved before starting the import and then reinserted into 1015 ``sys.modules`` when the fresh import is complete. 1016 1017 Module and package deprecation messages are suppressed during this import 1018 if *deprecated* is ``True``. 1019 1020 This function will raise :exc:`ImportError` if the named module cannot be 1021 imported. 1022 1023 Example use:: 1024 1025 # Get copies of the warnings module for testing without affecting the 1026 # version being used by the rest of the test suite. One copy uses the 1027 # C implementation, the other is forced to use the pure Python fallback 1028 # implementation 1029 py_warnings = import_fresh_module('warnings', blocked=['_warnings']) 1030 c_warnings = import_fresh_module('warnings', fresh=['_warnings']) 1031 1032 .. versionadded:: 3.1 1033 1034 1035.. function:: modules_setup() 1036 1037 Return a copy of :data:`sys.modules`. 1038 1039 1040.. function:: modules_cleanup(oldmodules) 1041 1042 Remove modules except for *oldmodules* and ``encodings`` in order to 1043 preserve internal cache. 1044 1045 1046.. function:: threading_setup() 1047 1048 Return current thread count and copy of dangling threads. 1049 1050 1051.. function:: threading_cleanup(*original_values) 1052 1053 Cleanup up threads not specified in *original_values*. Designed to emit 1054 a warning if a test leaves running threads in the background. 1055 1056 1057.. function:: join_thread(thread, timeout=30.0) 1058 1059 Join a *thread* within *timeout*. Raise an :exc:`AssertionError` if thread 1060 is still alive after *timeout* seconds. 1061 1062 1063.. function:: reap_children() 1064 1065 Use this at the end of ``test_main`` whenever sub-processes are started. 1066 This will help ensure that no extra children (zombies) stick around to 1067 hog resources and create problems when looking for refleaks. 1068 1069 1070.. function:: get_attribute(obj, name) 1071 1072 Get an attribute, raising :exc:`unittest.SkipTest` if :exc:`AttributeError` 1073 is raised. 1074 1075 1076.. function:: bind_port(sock, host=HOST) 1077 1078 Bind the socket to a free port and return the port number. Relies on 1079 ephemeral ports in order to ensure we are using an unbound port. This is 1080 important as many tests may be running simultaneously, especially in a 1081 buildbot environment. This method raises an exception if the 1082 ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is 1083 :const:`~socket.SOCK_STREAM`, and the socket has 1084 :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it. 1085 Tests should never set these socket options for TCP/IP sockets. 1086 The only case for setting these options is testing multicasting via 1087 multiple UDP sockets. 1088 1089 Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is 1090 available (i.e. on Windows), it will be set on the socket. This will 1091 prevent anyone else from binding to our host/port for the duration of the 1092 test. 1093 1094 1095.. function:: bind_unix_socket(sock, addr) 1096 1097 Bind a unix socket, raising :exc:`unittest.SkipTest` if 1098 :exc:`PermissionError` is raised. 1099 1100 1101.. function:: catch_threading_exception() 1102 1103 Context manager catching :class:`threading.Thread` exception using 1104 :func:`threading.excepthook`. 1105 1106 Attributes set when an exception is catched: 1107 1108 * ``exc_type`` 1109 * ``exc_value`` 1110 * ``exc_traceback`` 1111 * ``thread`` 1112 1113 See :func:`threading.excepthook` documentation. 1114 1115 These attributes are deleted at the context manager exit. 1116 1117 Usage:: 1118 1119 with support.catch_threading_exception() as cm: 1120 # code spawning a thread which raises an exception 1121 ... 1122 1123 # check the thread exception, use cm attributes: 1124 # exc_type, exc_value, exc_traceback, thread 1125 ... 1126 1127 # exc_type, exc_value, exc_traceback, thread attributes of cm no longer 1128 # exists at this point 1129 # (to avoid reference cycles) 1130 1131 .. versionadded:: 3.8 1132 1133 1134.. function:: catch_unraisable_exception() 1135 1136 Context manager catching unraisable exception using 1137 :func:`sys.unraisablehook`. 1138 1139 Storing the exception value (``cm.unraisable.exc_value``) creates a 1140 reference cycle. The reference cycle is broken explicitly when the context 1141 manager exits. 1142 1143 Storing the object (``cm.unraisable.object``) can resurrect it if it is set 1144 to an object which is being finalized. Exiting the context manager clears 1145 the stored object. 1146 1147 Usage:: 1148 1149 with support.catch_unraisable_exception() as cm: 1150 # code creating an "unraisable exception" 1151 ... 1152 1153 # check the unraisable exception: use cm.unraisable 1154 ... 1155 1156 # cm.unraisable attribute no longer exists at this point 1157 # (to break a reference cycle) 1158 1159 .. versionadded:: 3.8 1160 1161 1162.. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM) 1163 1164 Returns an unused port that should be suitable for binding. This is 1165 achieved by creating a temporary socket with the same family and type as 1166 the ``sock`` parameter (default is :const:`~socket.AF_INET`, 1167 :const:`~socket.SOCK_STREAM`), 1168 and binding it to the specified host address (defaults to ``0.0.0.0``) 1169 with the port set to 0, eliciting an unused ephemeral port from the OS. 1170 The temporary socket is then closed and deleted, and the ephemeral port is 1171 returned. 1172 1173 Either this method or :func:`bind_port` should be used for any tests 1174 where a server socket needs to be bound to a particular port for the 1175 duration of the test. 1176 Which one to use depends on whether the calling code is creating a Python 1177 socket, or if an unused port needs to be provided in a constructor 1178 or passed to an external program (i.e. the ``-accept`` argument to 1179 openssl's s_server mode). Always prefer :func:`bind_port` over 1180 :func:`find_unused_port` where possible. Using a hard coded port is 1181 discouraged since it can make multiple instances of the test impossible to 1182 run simultaneously, which is a problem for buildbots. 1183 1184 1185.. function:: load_package_tests(pkg_dir, loader, standard_tests, pattern) 1186 1187 Generic implementation of the :mod:`unittest` ``load_tests`` protocol for 1188 use in test packages. *pkg_dir* is the root directory of the package; 1189 *loader*, *standard_tests*, and *pattern* are the arguments expected by 1190 ``load_tests``. In simple cases, the test package's ``__init__.py`` 1191 can be the following:: 1192 1193 import os 1194 from test.support import load_package_tests 1195 1196 def load_tests(*args): 1197 return load_package_tests(os.path.dirname(__file__), *args) 1198 1199 1200.. function:: fs_is_case_insensitive(directory) 1201 1202 Return ``True`` if the file system for *directory* is case-insensitive. 1203 1204 1205.. function:: detect_api_mismatch(ref_api, other_api, *, ignore=()) 1206 1207 Returns the set of attributes, functions or methods of *ref_api* not 1208 found on *other_api*, except for a defined list of items to be 1209 ignored in this check specified in *ignore*. 1210 1211 By default this skips private attributes beginning with '_' but 1212 includes all magic methods, i.e. those starting and ending in '__'. 1213 1214 .. versionadded:: 3.5 1215 1216 1217.. function:: patch(test_instance, object_to_patch, attr_name, new_value) 1218 1219 Override *object_to_patch.attr_name* with *new_value*. Also add 1220 cleanup procedure to *test_instance* to restore *object_to_patch* for 1221 *attr_name*. The *attr_name* should be a valid attribute for 1222 *object_to_patch*. 1223 1224 1225.. function:: run_in_subinterp(code) 1226 1227 Run *code* in subinterpreter. Raise :exc:`unittest.SkipTest` if 1228 :mod:`tracemalloc` is enabled. 1229 1230 1231.. function:: check_free_after_iterating(test, iter, cls, args=()) 1232 1233 Assert that *iter* is deallocated after iterating. 1234 1235 1236.. function:: missing_compiler_executable(cmd_names=[]) 1237 1238 Check for the existence of the compiler executables whose names are listed 1239 in *cmd_names* or all the compiler executables when *cmd_names* is empty 1240 and return the first missing executable or ``None`` when none is found 1241 missing. 1242 1243 1244.. function:: check__all__(test_case, module, name_of_module=None, extra=(), blacklist=()) 1245 1246 Assert that the ``__all__`` variable of *module* contains all public names. 1247 1248 The module's public names (its API) are detected automatically 1249 based on whether they match the public name convention and were defined in 1250 *module*. 1251 1252 The *name_of_module* argument can specify (as a string or tuple thereof) what 1253 module(s) an API could be defined in order to be detected as a public 1254 API. One case for this is when *module* imports part of its public API from 1255 other modules, possibly a C backend (like ``csv`` and its ``_csv``). 1256 1257 The *extra* argument can be a set of names that wouldn't otherwise be automatically 1258 detected as "public", like objects without a proper ``__module__`` 1259 attribute. If provided, it will be added to the automatically detected ones. 1260 1261 The *blacklist* argument can be a set of names that must not be treated as part of 1262 the public API even though their names indicate otherwise. 1263 1264 Example use:: 1265 1266 import bar 1267 import foo 1268 import unittest 1269 from test import support 1270 1271 class MiscTestCase(unittest.TestCase): 1272 def test__all__(self): 1273 support.check__all__(self, foo) 1274 1275 class OtherTestCase(unittest.TestCase): 1276 def test__all__(self): 1277 extra = {'BAR_CONST', 'FOO_CONST'} 1278 blacklist = {'baz'} # Undocumented name. 1279 # bar imports part of its API from _bar. 1280 support.check__all__(self, bar, ('bar', '_bar'), 1281 extra=extra, blacklist=blacklist) 1282 1283 .. versionadded:: 3.6 1284 1285 1286The :mod:`test.support` module defines the following classes: 1287 1288.. class:: TransientResource(exc, **kwargs) 1289 1290 Instances are a context manager that raises :exc:`ResourceDenied` if the 1291 specified exception type is raised. Any keyword arguments are treated as 1292 attribute/value pairs to be compared against any exception raised within the 1293 :keyword:`with` statement. Only if all pairs match properly against 1294 attributes on the exception is :exc:`ResourceDenied` raised. 1295 1296 1297.. class:: EnvironmentVarGuard() 1298 1299 Class used to temporarily set or unset environment variables. Instances can 1300 be used as a context manager and have a complete dictionary interface for 1301 querying/modifying the underlying ``os.environ``. After exit from the 1302 context manager all changes to environment variables done through this 1303 instance will be rolled back. 1304 1305 .. versionchanged:: 3.1 1306 Added dictionary interface. 1307 1308.. method:: EnvironmentVarGuard.set(envvar, value) 1309 1310 Temporarily set the environment variable ``envvar`` to the value of 1311 ``value``. 1312 1313 1314.. method:: EnvironmentVarGuard.unset(envvar) 1315 1316 Temporarily unset the environment variable ``envvar``. 1317 1318 1319.. class:: SuppressCrashReport() 1320 1321 A context manager used to try to prevent crash dialog popups on tests that 1322 are expected to crash a subprocess. 1323 1324 On Windows, it disables Windows Error Reporting dialogs using 1325 `SetErrorMode <https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx>`_. 1326 1327 On UNIX, :func:`resource.setrlimit` is used to set 1328 :attr:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file 1329 creation. 1330 1331 On both platforms, the old value is restored by :meth:`__exit__`. 1332 1333 1334.. class:: CleanImport(*module_names) 1335 1336 A context manager to force import to return a new module reference. This 1337 is useful for testing module-level behaviors, such as the emission of a 1338 DeprecationWarning on import. Example usage:: 1339 1340 with CleanImport('foo'): 1341 importlib.import_module('foo') # New reference. 1342 1343 1344.. class:: DirsOnSysPath(*paths) 1345 1346 A context manager to temporarily add directories to sys.path. 1347 1348 This makes a copy of :data:`sys.path`, appends any directories given 1349 as positional arguments, then reverts :data:`sys.path` to the copied 1350 settings when the context ends. 1351 1352 Note that *all* :data:`sys.path` modifications in the body of the 1353 context manager, including replacement of the object, 1354 will be reverted at the end of the block. 1355 1356 1357.. class:: SaveSignals() 1358 1359 Class to save and restore signal handlers registered by the Python signal 1360 handler. 1361 1362 1363.. class:: Matcher() 1364 1365 .. method:: matches(self, d, **kwargs) 1366 1367 Try to match a single dict with the supplied arguments. 1368 1369 1370 .. method:: match_value(self, k, dv, v) 1371 1372 Try to match a single stored value (*dv*) with a supplied value (*v*). 1373 1374 1375.. class:: WarningsRecorder() 1376 1377 Class used to record warnings for unit tests. See documentation of 1378 :func:`check_warnings` above for more details. 1379 1380 1381.. class:: BasicTestRunner() 1382 1383 .. method:: run(test) 1384 1385 Run *test* and return the result. 1386 1387 1388.. class:: TestHandler(logging.handlers.BufferingHandler) 1389 1390 Class for logging support. 1391 1392 1393.. class:: FakePath(path) 1394 1395 Simple :term:`path-like object`. It implements the :meth:`__fspath__` 1396 method which just returns the *path* argument. If *path* is an exception, 1397 it will be raised in :meth:`!__fspath__`. 1398 1399 1400:mod:`test.support.script_helper` --- Utilities for the Python execution tests 1401============================================================================== 1402 1403.. module:: test.support.script_helper 1404 :synopsis: Support for Python's script execution tests. 1405 1406 1407The :mod:`test.support.script_helper` module provides support for Python's 1408script execution tests. 1409 1410.. function:: interpreter_requires_environment() 1411 1412 Return ``True`` if ``sys.executable interpreter`` requires environment 1413 variables in order to be able to run at all. 1414 1415 This is designed to be used with ``@unittest.skipIf()`` to annotate tests 1416 that need to use an ``assert_python*()`` function to launch an isolated 1417 mode (``-I``) or no environment mode (``-E``) sub-interpreter process. 1418 1419 A normal build & test does not run into this situation but it can happen 1420 when trying to run the standard library test suite from an interpreter that 1421 doesn't have an obvious home with Python's current home finding logic. 1422 1423 Setting :envvar:`PYTHONHOME` is one way to get most of the testsuite to run 1424 in that situation. :envvar:`PYTHONPATH` or :envvar:`PYTHONUSERSITE` are 1425 other common environment variables that might impact whether or not the 1426 interpreter can start. 1427 1428 1429.. function:: run_python_until_end(*args, **env_vars) 1430 1431 Set up the environment based on *env_vars* for running the interpreter 1432 in a subprocess. The values can include ``__isolated``, ``__cleanenv``, 1433 ``__cwd``, and ``TERM``. 1434 1435 1436.. function:: assert_python_ok(*args, **env_vars) 1437 1438 Assert that running the interpreter with *args* and optional environment 1439 variables *env_vars* succeeds (``rc == 0``) and return a ``(return code, 1440 stdout, stderr)`` tuple. 1441 1442 If the ``__cleanenv`` keyword is set, *env_vars* is used as a fresh 1443 environment. 1444 1445 Python is started in isolated mode (command line option ``-I``), 1446 except if the ``__isolated`` keyword is set to ``False``. 1447 1448 1449.. function:: assert_python_failure(*args, **env_vars) 1450 1451 Assert that running the interpreter with *args* and optional environment 1452 variables *env_vars* fails (``rc != 0``) and return a ``(return code, 1453 stdout, stderr)`` tuple. 1454 1455 See :func:`assert_python_ok` for more options. 1456 1457 1458.. function:: spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw) 1459 1460 Run a Python subprocess with the given arguments. 1461 1462 *kw* is extra keyword args to pass to :func:`subprocess.Popen`. Returns a 1463 :class:`subprocess.Popen` object. 1464 1465 1466.. function:: kill_python(p) 1467 1468 Run the given :class:`subprocess.Popen` process until completion and return 1469 stdout. 1470 1471 1472.. function:: make_script(script_dir, script_basename, source, omit_suffix=False) 1473 1474 Create script containing *source* in path *script_dir* and *script_basename*. 1475 If *omit_suffix* is ``False``, append ``.py`` to the name. Return the full 1476 script path. 1477 1478 1479.. function:: make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None) 1480 1481 Create zip file at *zip_dir* and *zip_basename* with extension ``zip`` which 1482 contains the files in *script_name*. *name_in_zip* is the archive name. 1483 Return a tuple containing ``(full path, full path of archive name)``. 1484 1485 1486.. function:: make_pkg(pkg_dir, init_source='') 1487 1488 Create a directory named *pkg_dir* containing an ``__init__`` file with 1489 *init_source* as its contents. 1490 1491 1492.. function:: make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, \ 1493 source, depth=1, compiled=False) 1494 1495 Create a zip package directory with a path of *zip_dir* and *zip_basename* 1496 containing an empty ``__init__`` file and a file *script_basename* 1497 containing the *source*. If *compiled* is ``True``, both source files will 1498 be compiled and added to the zip package. Return a tuple of the full zip 1499 path and the archive name for the zip file. 1500