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 <[email protected]> 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:: LOOPBACK_TIMEOUT 251 252 Timeout in seconds for tests using a network server listening on the network 253 local loopback interface like ``127.0.0.1``. 254 255 The timeout is long enough to prevent test failure: it takes into account 256 that the client and the server can run in different threads or even 257 different processes. 258 259 The timeout should be long enough for :meth:`~socket.socket.connect`, 260 :meth:`~socket.socket.recv` and :meth:`~socket.socket.send` methods of 261 :class:`socket.socket`. 262 263 Its default value is 5 seconds. 264 265 See also :data:`INTERNET_TIMEOUT`. 266 267 268.. data:: INTERNET_TIMEOUT 269 270 Timeout in seconds for network requests going to the internet. 271 272 The timeout is short enough to prevent a test to wait for too long if the 273 internet request is blocked for whatever reason. 274 275 Usually, a timeout using :data:`INTERNET_TIMEOUT` should not mark a test as 276 failed, but skip the test instead: see 277 :func:`~test.support.socket_helper.transient_internet`. 278 279 Its default value is 1 minute. 280 281 See also :data:`LOOPBACK_TIMEOUT`. 282 283 284.. data:: SHORT_TIMEOUT 285 286 Timeout in seconds to mark a test as failed if the test takes "too long". 287 288 The timeout value depends on the regrtest ``--timeout`` command line option. 289 290 If a test using :data:`SHORT_TIMEOUT` starts to fail randomly on slow 291 buildbots, use :data:`LONG_TIMEOUT` instead. 292 293 Its default value is 30 seconds. 294 295 296.. data:: LONG_TIMEOUT 297 298 Timeout in seconds to detect when a test hangs. 299 300 It is long enough to reduce the risk of test failure on the slowest Python 301 buildbots. It should not be used to mark a test as failed if the test takes 302 "too long". The timeout value depends on the regrtest ``--timeout`` command 303 line option. 304 305 Its default value is 5 minutes. 306 307 See also :data:`LOOPBACK_TIMEOUT`, :data:`INTERNET_TIMEOUT` and 308 :data:`SHORT_TIMEOUT`. 309 310 311.. data:: PGO 312 313 Set when tests can be skipped when they are not useful for PGO. 314 315 316.. data:: PIPE_MAX_SIZE 317 318 A constant that is likely larger than the underlying OS pipe buffer size, 319 to make writes blocking. 320 321 322.. data:: SOCK_MAX_SIZE 323 324 A constant that is likely larger than the underlying OS socket buffer size, 325 to make writes blocking. 326 327 328.. data:: TEST_SUPPORT_DIR 329 330 Set to the top level directory that contains :mod:`test.support`. 331 332 333.. data:: TEST_HOME_DIR 334 335 Set to the top level directory for the test package. 336 337 338.. data:: TEST_DATA_DIR 339 340 Set to the ``data`` directory within the test package. 341 342 343.. data:: MAX_Py_ssize_t 344 345 Set to :data:`sys.maxsize` for big memory tests. 346 347 348.. data:: max_memuse 349 350 Set by :func:`set_memlimit` as the memory limit for big memory tests. 351 Limited by :data:`MAX_Py_ssize_t`. 352 353 354.. data:: real_max_memuse 355 356 Set by :func:`set_memlimit` as the memory limit for big memory tests. Not 357 limited by :data:`MAX_Py_ssize_t`. 358 359 360.. data:: MISSING_C_DOCSTRINGS 361 362 Set to ``True`` if Python is built without docstrings (the 363 :c:macro:`WITH_DOC_STRINGS` macro is not defined). 364 See the :option:`configure --without-doc-strings <--without-doc-strings>` option. 365 366 See also the :data:`HAVE_DOCSTRINGS` variable. 367 368 369.. data:: HAVE_DOCSTRINGS 370 371 Set to ``True`` if function docstrings are available. 372 See the :option:`python -OO <-O>` option, which strips docstrings of functions implemented in Python. 373 374 See also the :data:`MISSING_C_DOCSTRINGS` variable. 375 376 377.. data:: TEST_HTTP_URL 378 379 Define the URL of a dedicated HTTP server for the network tests. 380 381 382.. data:: ALWAYS_EQ 383 384 Object that is equal to anything. Used to test mixed type comparison. 385 386 387.. data:: NEVER_EQ 388 389 Object that is not equal to anything (even to :data:`ALWAYS_EQ`). 390 Used to test mixed type comparison. 391 392 393.. data:: LARGEST 394 395 Object that is greater than anything (except itself). 396 Used to test mixed type comparison. 397 398 399.. data:: SMALLEST 400 401 Object that is less than anything (except itself). 402 Used to test mixed type comparison. 403 404 405The :mod:`test.support` module defines the following functions: 406 407.. function:: is_resource_enabled(resource) 408 409 Return ``True`` if *resource* is enabled and available. The list of 410 available resources is only set when :mod:`test.regrtest` is executing the 411 tests. 412 413 414.. function:: python_is_optimized() 415 416 Return ``True`` if Python was not built with ``-O0`` or ``-Og``. 417 418 419.. function:: with_pymalloc() 420 421 Return :data:`_testcapi.WITH_PYMALLOC`. 422 423 424.. function:: requires(resource, msg=None) 425 426 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the 427 argument to :exc:`ResourceDenied` if it is raised. Always returns 428 ``True`` if called by a function whose ``__name__`` is ``'__main__'``. 429 Used when tests are executed by :mod:`test.regrtest`. 430 431 432.. function:: sortdict(dict) 433 434 Return a repr of *dict* with keys sorted. 435 436 437.. function:: findfile(filename, subdir=None) 438 439 Return the path to the file named *filename*. If no match is found 440 *filename* is returned. This does not equal a failure since it could be the 441 path to the file. 442 443 Setting *subdir* indicates a relative path to use to find the file 444 rather than looking directly in the path directories. 445 446 447.. function:: match_test(test) 448 449 Determine whether *test* matches the patterns set in :func:`set_match_tests`. 450 451 452.. function:: set_match_tests(accept_patterns=None, ignore_patterns=None) 453 454 Define match patterns on test filenames and test method names for filtering tests. 455 456 457.. function:: run_unittest(*classes) 458 459 Execute :class:`unittest.TestCase` subclasses passed to the function. The 460 function scans the classes for methods starting with the prefix ``test_`` 461 and executes the tests individually. 462 463 It is also legal to pass strings as parameters; these should be keys in 464 ``sys.modules``. Each associated module will be scanned by 465 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the 466 following :func:`test_main` function:: 467 468 def test_main(): 469 support.run_unittest(__name__) 470 471 This will run all tests defined in the named module. 472 473 474.. function:: run_doctest(module, verbosity=None, optionflags=0) 475 476 Run :func:`doctest.testmod` on the given *module*. Return 477 ``(failure_count, test_count)``. 478 479 If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity 480 set to :data:`verbose`. Otherwise, it is run with verbosity set to 481 ``None``. *optionflags* is passed as ``optionflags`` to 482 :func:`doctest.testmod`. 483 484 485.. function:: setswitchinterval(interval) 486 487 Set the :func:`sys.setswitchinterval` to the given *interval*. Defines 488 a minimum interval for Android systems to prevent the system from hanging. 489 490 491.. function:: check_impl_detail(**guards) 492 493 Use this check to guard CPython's implementation-specific tests or to 494 run them only on the implementations guarded by the arguments. This 495 function returns ``True`` or ``False`` depending on the host platform. 496 Example usage:: 497 498 check_impl_detail() # Only on CPython (default). 499 check_impl_detail(jython=True) # Only on Jython. 500 check_impl_detail(cpython=False) # Everywhere except CPython. 501 502 503.. function:: set_memlimit(limit) 504 505 Set the values for :data:`max_memuse` and :data:`real_max_memuse` for big 506 memory tests. 507 508 509.. function:: record_original_stdout(stdout) 510 511 Store the value from *stdout*. It is meant to hold the stdout at the 512 time the regrtest began. 513 514 515.. function:: get_original_stdout() 516 517 Return the original stdout set by :func:`record_original_stdout` or 518 ``sys.stdout`` if it's not set. 519 520 521.. function:: args_from_interpreter_flags() 522 523 Return a list of command line arguments reproducing the current settings 524 in ``sys.flags`` and ``sys.warnoptions``. 525 526 527.. function:: optim_args_from_interpreter_flags() 528 529 Return a list of command line arguments reproducing the current 530 optimization settings in ``sys.flags``. 531 532 533.. function:: captured_stdin() 534 captured_stdout() 535 captured_stderr() 536 537 A context managers that temporarily replaces the named stream with 538 :class:`io.StringIO` object. 539 540 Example use with output streams:: 541 542 with captured_stdout() as stdout, captured_stderr() as stderr: 543 print("hello") 544 print("error", file=sys.stderr) 545 assert stdout.getvalue() == "hello\n" 546 assert stderr.getvalue() == "error\n" 547 548 Example use with input stream:: 549 550 with captured_stdin() as stdin: 551 stdin.write('hello\n') 552 stdin.seek(0) 553 # call test code that consumes from sys.stdin 554 captured = input() 555 self.assertEqual(captured, "hello") 556 557 558.. function:: disable_faulthandler() 559 560 A context manager that temporary disables :mod:`faulthandler`. 561 562 563.. function:: gc_collect() 564 565 Force as many objects as possible to be collected. This is needed because 566 timely deallocation is not guaranteed by the garbage collector. This means 567 that ``__del__`` methods may be called later than expected and weakrefs 568 may remain alive for longer than expected. 569 570 571.. function:: disable_gc() 572 573 A context manager that disables the garbage collector on entry. On 574 exit, the garbage collector is restored to its prior state. 575 576 577.. function:: swap_attr(obj, attr, new_val) 578 579 Context manager to swap out an attribute with a new object. 580 581 Usage:: 582 583 with swap_attr(obj, "attr", 5): 584 ... 585 586 This will set ``obj.attr`` to 5 for the duration of the ``with`` block, 587 restoring the old value at the end of the block. If ``attr`` doesn't 588 exist on ``obj``, it will be created and then deleted at the end of the 589 block. 590 591 The old value (or ``None`` if it doesn't exist) will be assigned to the 592 target of the "as" clause, if there is one. 593 594 595.. function:: swap_item(obj, attr, new_val) 596 597 Context manager to swap out an item with a new object. 598 599 Usage:: 600 601 with swap_item(obj, "item", 5): 602 ... 603 604 This will set ``obj["item"]`` to 5 for the duration of the ``with`` block, 605 restoring the old value at the end of the block. If ``item`` doesn't 606 exist on ``obj``, it will be created and then deleted at the end of the 607 block. 608 609 The old value (or ``None`` if it doesn't exist) will be assigned to the 610 target of the "as" clause, if there is one. 611 612 613.. function:: flush_std_streams() 614 615 Call the ``flush()`` method on :data:`sys.stdout` and then on 616 :data:`sys.stderr`. It can be used to make sure that the logs order is 617 consistent before writing into stderr. 618 619 .. versionadded:: 3.11 620 621 622.. function:: print_warning(msg) 623 624 Print a warning into :data:`sys.__stderr__`. Format the message as: 625 ``f"Warning -- {msg}"``. If *msg* is made of multiple lines, add 626 ``"Warning -- "`` prefix to each line. 627 628 .. versionadded:: 3.9 629 630 631.. function:: wait_process(pid, *, exitcode, timeout=None) 632 633 Wait until process *pid* completes and check that the process exit code is 634 *exitcode*. 635 636 Raise an :exc:`AssertionError` if the process exit code is not equal to 637 *exitcode*. 638 639 If the process runs longer than *timeout* seconds (:data:`SHORT_TIMEOUT` by 640 default), kill the process and raise an :exc:`AssertionError`. The timeout 641 feature is not available on Windows. 642 643 .. versionadded:: 3.9 644 645 646.. function:: calcobjsize(fmt) 647 648 Return the size of the :c:type:`PyObject` whose structure members are 649 defined by *fmt*. The returned value includes the size of the Python object header and alignment. 650 651 652.. function:: calcvobjsize(fmt) 653 654 Return the size of the :c:type:`PyVarObject` whose structure members are 655 defined by *fmt*. The returned value includes the size of the Python object header and alignment. 656 657 658.. function:: checksizeof(test, o, size) 659 660 For testcase *test*, assert that the ``sys.getsizeof`` for *o* plus the GC 661 header size equals *size*. 662 663 664.. decorator:: anticipate_failure(condition) 665 666 A decorator to conditionally mark tests with 667 :func:`unittest.expectedFailure`. Any use of this decorator should 668 have an associated comment identifying the relevant tracker issue. 669 670 671.. function:: system_must_validate_cert(f) 672 673 A decorator that skips the decorated test on TLS certification validation failures. 674 675 676.. decorator:: run_with_locale(catstr, *locales) 677 678 A decorator for running a function in a different locale, correctly 679 resetting it after it has finished. *catstr* is the locale category as 680 a string (for example ``"LC_ALL"``). The *locales* passed will be tried 681 sequentially, and the first valid locale will be used. 682 683 684.. decorator:: run_with_tz(tz) 685 686 A decorator for running a function in a specific timezone, correctly 687 resetting it after it has finished. 688 689 690.. decorator:: requires_freebsd_version(*min_version) 691 692 Decorator for the minimum version when running test on FreeBSD. If the 693 FreeBSD version is less than the minimum, the test is skipped. 694 695 696.. decorator:: requires_linux_version(*min_version) 697 698 Decorator for the minimum version when running test on Linux. If the 699 Linux version is less than the minimum, the test is skipped. 700 701 702.. decorator:: requires_mac_version(*min_version) 703 704 Decorator for the minimum version when running test on macOS. If the 705 macOS version is less than the minimum, the test is skipped. 706 707 708.. decorator:: requires_IEEE_754 709 710 Decorator for skipping tests on non-IEEE 754 platforms. 711 712 713.. decorator:: requires_zlib 714 715 Decorator for skipping tests if :mod:`zlib` doesn't exist. 716 717 718.. decorator:: requires_gzip 719 720 Decorator for skipping tests if :mod:`gzip` doesn't exist. 721 722 723.. decorator:: requires_bz2 724 725 Decorator for skipping tests if :mod:`bz2` doesn't exist. 726 727 728.. decorator:: requires_lzma 729 730 Decorator for skipping tests if :mod:`lzma` doesn't exist. 731 732 733.. decorator:: requires_resource(resource) 734 735 Decorator for skipping tests if *resource* is not available. 736 737 738.. decorator:: requires_docstrings 739 740 Decorator for only running the test if :data:`HAVE_DOCSTRINGS`. 741 742 743.. decorator:: cpython_only 744 745 Decorator for tests only applicable to CPython. 746 747 748.. decorator:: impl_detail(msg=None, **guards) 749 750 Decorator for invoking :func:`check_impl_detail` on *guards*. If that 751 returns ``False``, then uses *msg* as the reason for skipping the test. 752 753 754.. decorator:: no_tracing 755 756 Decorator to temporarily turn off tracing for the duration of the test. 757 758 759.. decorator:: refcount_test 760 761 Decorator for tests which involve reference counting. The decorator does 762 not run the test if it is not run by CPython. Any trace function is unset 763 for the duration of the test to prevent unexpected refcounts caused by 764 the trace function. 765 766 767.. decorator:: bigmemtest(size, memuse, dry_run=True) 768 769 Decorator for bigmem tests. 770 771 *size* is a requested size for the test (in arbitrary, test-interpreted 772 units.) *memuse* is the number of bytes per unit for the test, or a good 773 estimate of it. For example, a test that needs two byte buffers, of 4 GiB 774 each, could be decorated with ``@bigmemtest(size=_4G, memuse=2)``. 775 776 The *size* argument is normally passed to the decorated test method as an 777 extra argument. If *dry_run* is ``True``, the value passed to the test 778 method may be less than the requested value. If *dry_run* is ``False``, it 779 means the test doesn't support dummy runs when ``-M`` is not specified. 780 781 782.. decorator:: bigaddrspacetest 783 784 Decorator for tests that fill the address space. 785 786 787.. function:: check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None) 788 789 Test for syntax errors in *statement* by attempting to compile *statement*. 790 *testcase* is the :mod:`unittest` instance for the test. *errtext* is the 791 regular expression which should match the string representation of the 792 raised :exc:`SyntaxError`. If *lineno* is not ``None``, compares to 793 the line of the exception. If *offset* is not ``None``, compares to 794 the offset of the exception. 795 796 797.. function:: open_urlresource(url, *args, **kw) 798 799 Open *url*. If open fails, raises :exc:`TestFailed`. 800 801 802.. function:: reap_children() 803 804 Use this at the end of ``test_main`` whenever sub-processes are started. 805 This will help ensure that no extra children (zombies) stick around to 806 hog resources and create problems when looking for refleaks. 807 808 809.. function:: get_attribute(obj, name) 810 811 Get an attribute, raising :exc:`unittest.SkipTest` if :exc:`AttributeError` 812 is raised. 813 814 815.. function:: catch_unraisable_exception() 816 817 Context manager catching unraisable exception using 818 :func:`sys.unraisablehook`. 819 820 Storing the exception value (``cm.unraisable.exc_value``) creates a 821 reference cycle. The reference cycle is broken explicitly when the context 822 manager exits. 823 824 Storing the object (``cm.unraisable.object``) can resurrect it if it is set 825 to an object which is being finalized. Exiting the context manager clears 826 the stored object. 827 828 Usage:: 829 830 with support.catch_unraisable_exception() as cm: 831 # code creating an "unraisable exception" 832 ... 833 834 # check the unraisable exception: use cm.unraisable 835 ... 836 837 # cm.unraisable attribute no longer exists at this point 838 # (to break a reference cycle) 839 840 .. versionadded:: 3.8 841 842 843.. function:: load_package_tests(pkg_dir, loader, standard_tests, pattern) 844 845 Generic implementation of the :mod:`unittest` ``load_tests`` protocol for 846 use in test packages. *pkg_dir* is the root directory of the package; 847 *loader*, *standard_tests*, and *pattern* are the arguments expected by 848 ``load_tests``. In simple cases, the test package's ``__init__.py`` 849 can be the following:: 850 851 import os 852 from test.support import load_package_tests 853 854 def load_tests(*args): 855 return load_package_tests(os.path.dirname(__file__), *args) 856 857 858.. function:: detect_api_mismatch(ref_api, other_api, *, ignore=()) 859 860 Returns the set of attributes, functions or methods of *ref_api* not 861 found on *other_api*, except for a defined list of items to be 862 ignored in this check specified in *ignore*. 863 864 By default this skips private attributes beginning with '_' but 865 includes all magic methods, i.e. those starting and ending in '__'. 866 867 .. versionadded:: 3.5 868 869 870.. function:: patch(test_instance, object_to_patch, attr_name, new_value) 871 872 Override *object_to_patch.attr_name* with *new_value*. Also add 873 cleanup procedure to *test_instance* to restore *object_to_patch* for 874 *attr_name*. The *attr_name* should be a valid attribute for 875 *object_to_patch*. 876 877 878.. function:: run_in_subinterp(code) 879 880 Run *code* in subinterpreter. Raise :exc:`unittest.SkipTest` if 881 :mod:`tracemalloc` is enabled. 882 883 884.. function:: check_free_after_iterating(test, iter, cls, args=()) 885 886 Assert instances of *cls* are deallocated after iterating. 887 888 889.. function:: missing_compiler_executable(cmd_names=[]) 890 891 Check for the existence of the compiler executables whose names are listed 892 in *cmd_names* or all the compiler executables when *cmd_names* is empty 893 and return the first missing executable or ``None`` when none is found 894 missing. 895 896 897.. function:: check__all__(test_case, module, name_of_module=None, extra=(), not_exported=()) 898 899 Assert that the ``__all__`` variable of *module* contains all public names. 900 901 The module's public names (its API) are detected automatically 902 based on whether they match the public name convention and were defined in 903 *module*. 904 905 The *name_of_module* argument can specify (as a string or tuple thereof) what 906 module(s) an API could be defined in order to be detected as a public 907 API. One case for this is when *module* imports part of its public API from 908 other modules, possibly a C backend (like ``csv`` and its ``_csv``). 909 910 The *extra* argument can be a set of names that wouldn't otherwise be automatically 911 detected as "public", like objects without a proper ``__module__`` 912 attribute. If provided, it will be added to the automatically detected ones. 913 914 The *not_exported* argument can be a set of names that must not be treated 915 as part of the public API even though their names indicate otherwise. 916 917 Example use:: 918 919 import bar 920 import foo 921 import unittest 922 from test import support 923 924 class MiscTestCase(unittest.TestCase): 925 def test__all__(self): 926 support.check__all__(self, foo) 927 928 class OtherTestCase(unittest.TestCase): 929 def test__all__(self): 930 extra = {'BAR_CONST', 'FOO_CONST'} 931 not_exported = {'baz'} # Undocumented name. 932 # bar imports part of its API from _bar. 933 support.check__all__(self, bar, ('bar', '_bar'), 934 extra=extra, not_exported=not_exported) 935 936 .. versionadded:: 3.6 937 938.. function:: skip_if_broken_multiprocessing_synchronize() 939 940 Skip tests if the :mod:`multiprocessing.synchronize` module is missing, if 941 there is no available semaphore implementation, or if creating a lock raises 942 an :exc:`OSError`. 943 944 .. versionadded:: 3.10 945 946 947.. function:: check_disallow_instantiation(test_case, tp, *args, **kwds) 948 949 Assert that type *tp* cannot be instantiated using *args* and *kwds*. 950 951 .. versionadded:: 3.10 952 953 954.. function:: adjust_int_max_str_digits(max_digits) 955 956 This function returns a context manager that will change the global 957 :func:`sys.set_int_max_str_digits` setting for the duration of the 958 context to allow execution of test code that needs a different limit 959 on the number of digits when converting between an integer and string. 960 961 .. versionadded:: 3.11 962 963 964The :mod:`test.support` module defines the following classes: 965 966 967.. class:: SuppressCrashReport() 968 969 A context manager used to try to prevent crash dialog popups on tests that 970 are expected to crash a subprocess. 971 972 On Windows, it disables Windows Error Reporting dialogs using 973 `SetErrorMode <https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx>`_. 974 975 On UNIX, :func:`resource.setrlimit` is used to set 976 :attr:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file 977 creation. 978 979 On both platforms, the old value is restored by :meth:`__exit__`. 980 981 982.. class:: SaveSignals() 983 984 Class to save and restore signal handlers registered by the Python signal 985 handler. 986 987 .. method:: save(self) 988 989 Save the signal handlers to a dictionary mapping signal numbers to the 990 current signal handler. 991 992 .. method:: restore(self) 993 994 Set the signal numbers from the :meth:`save` dictionary to the saved 995 handler. 996 997 998.. class:: Matcher() 999 1000 .. method:: matches(self, d, **kwargs) 1001 1002 Try to match a single dict with the supplied arguments. 1003 1004 1005 .. method:: match_value(self, k, dv, v) 1006 1007 Try to match a single stored value (*dv*) with a supplied value (*v*). 1008 1009 1010.. class:: BasicTestRunner() 1011 1012 .. method:: run(test) 1013 1014 Run *test* and return the result. 1015 1016 1017:mod:`test.support.socket_helper` --- Utilities for socket tests 1018================================================================ 1019 1020.. module:: test.support.socket_helper 1021 :synopsis: Support for socket tests. 1022 1023 1024The :mod:`test.support.socket_helper` module provides support for socket tests. 1025 1026.. versionadded:: 3.9 1027 1028 1029.. data:: IPV6_ENABLED 1030 1031 Set to ``True`` if IPv6 is enabled on this host, ``False`` otherwise. 1032 1033 1034.. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM) 1035 1036 Returns an unused port that should be suitable for binding. This is 1037 achieved by creating a temporary socket with the same family and type as 1038 the ``sock`` parameter (default is :const:`~socket.AF_INET`, 1039 :const:`~socket.SOCK_STREAM`), 1040 and binding it to the specified host address (defaults to ``0.0.0.0``) 1041 with the port set to 0, eliciting an unused ephemeral port from the OS. 1042 The temporary socket is then closed and deleted, and the ephemeral port is 1043 returned. 1044 1045 Either this method or :func:`bind_port` should be used for any tests 1046 where a server socket needs to be bound to a particular port for the 1047 duration of the test. 1048 Which one to use depends on whether the calling code is creating a Python 1049 socket, or if an unused port needs to be provided in a constructor 1050 or passed to an external program (i.e. the ``-accept`` argument to 1051 openssl's s_server mode). Always prefer :func:`bind_port` over 1052 :func:`find_unused_port` where possible. Using a hard coded port is 1053 discouraged since it can make multiple instances of the test impossible to 1054 run simultaneously, which is a problem for buildbots. 1055 1056 1057.. function:: bind_port(sock, host=HOST) 1058 1059 Bind the socket to a free port and return the port number. Relies on 1060 ephemeral ports in order to ensure we are using an unbound port. This is 1061 important as many tests may be running simultaneously, especially in a 1062 buildbot environment. This method raises an exception if the 1063 ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is 1064 :const:`~socket.SOCK_STREAM`, and the socket has 1065 :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it. 1066 Tests should never set these socket options for TCP/IP sockets. 1067 The only case for setting these options is testing multicasting via 1068 multiple UDP sockets. 1069 1070 Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is 1071 available (i.e. on Windows), it will be set on the socket. This will 1072 prevent anyone else from binding to our host/port for the duration of the 1073 test. 1074 1075 1076.. function:: bind_unix_socket(sock, addr) 1077 1078 Bind a Unix socket, raising :exc:`unittest.SkipTest` if 1079 :exc:`PermissionError` is raised. 1080 1081 1082.. decorator:: skip_unless_bind_unix_socket 1083 1084 A decorator for running tests that require a functional ``bind()`` for Unix 1085 sockets. 1086 1087 1088.. function:: transient_internet(resource_name, *, timeout=30.0, errnos=()) 1089 1090 A context manager that raises :exc:`~test.support.ResourceDenied` when 1091 various issues with the internet connection manifest themselves as 1092 exceptions. 1093 1094 1095:mod:`test.support.script_helper` --- Utilities for the Python execution tests 1096============================================================================== 1097 1098.. module:: test.support.script_helper 1099 :synopsis: Support for Python's script execution tests. 1100 1101 1102The :mod:`test.support.script_helper` module provides support for Python's 1103script execution tests. 1104 1105.. function:: interpreter_requires_environment() 1106 1107 Return ``True`` if ``sys.executable interpreter`` requires environment 1108 variables in order to be able to run at all. 1109 1110 This is designed to be used with ``@unittest.skipIf()`` to annotate tests 1111 that need to use an ``assert_python*()`` function to launch an isolated 1112 mode (``-I``) or no environment mode (``-E``) sub-interpreter process. 1113 1114 A normal build & test does not run into this situation but it can happen 1115 when trying to run the standard library test suite from an interpreter that 1116 doesn't have an obvious home with Python's current home finding logic. 1117 1118 Setting :envvar:`PYTHONHOME` is one way to get most of the testsuite to run 1119 in that situation. :envvar:`PYTHONPATH` or :envvar:`PYTHONUSERSITE` are 1120 other common environment variables that might impact whether or not the 1121 interpreter can start. 1122 1123 1124.. function:: run_python_until_end(*args, **env_vars) 1125 1126 Set up the environment based on *env_vars* for running the interpreter 1127 in a subprocess. The values can include ``__isolated``, ``__cleanenv``, 1128 ``__cwd``, and ``TERM``. 1129 1130 .. versionchanged:: 3.9 1131 The function no longer strips whitespaces from *stderr*. 1132 1133 1134.. function:: assert_python_ok(*args, **env_vars) 1135 1136 Assert that running the interpreter with *args* and optional environment 1137 variables *env_vars* succeeds (``rc == 0``) and return a ``(return code, 1138 stdout, stderr)`` tuple. 1139 1140 If the *__cleanenv* keyword-only parameter is set, *env_vars* is used as a fresh 1141 environment. 1142 1143 Python is started in isolated mode (command line option ``-I``), 1144 except if the *__isolated* keyword-only parameter is set to ``False``. 1145 1146 .. versionchanged:: 3.9 1147 The function no longer strips whitespaces from *stderr*. 1148 1149 1150.. function:: assert_python_failure(*args, **env_vars) 1151 1152 Assert that running the interpreter with *args* and optional environment 1153 variables *env_vars* fails (``rc != 0``) and return a ``(return code, 1154 stdout, stderr)`` tuple. 1155 1156 See :func:`assert_python_ok` for more options. 1157 1158 .. versionchanged:: 3.9 1159 The function no longer strips whitespaces from *stderr*. 1160 1161 1162.. function:: spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw) 1163 1164 Run a Python subprocess with the given arguments. 1165 1166 *kw* is extra keyword args to pass to :func:`subprocess.Popen`. Returns a 1167 :class:`subprocess.Popen` object. 1168 1169 1170.. function:: kill_python(p) 1171 1172 Run the given :class:`subprocess.Popen` process until completion and return 1173 stdout. 1174 1175 1176.. function:: make_script(script_dir, script_basename, source, omit_suffix=False) 1177 1178 Create script containing *source* in path *script_dir* and *script_basename*. 1179 If *omit_suffix* is ``False``, append ``.py`` to the name. Return the full 1180 script path. 1181 1182 1183.. function:: make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None) 1184 1185 Create zip file at *zip_dir* and *zip_basename* with extension ``zip`` which 1186 contains the files in *script_name*. *name_in_zip* is the archive name. 1187 Return a tuple containing ``(full path, full path of archive name)``. 1188 1189 1190.. function:: make_pkg(pkg_dir, init_source='') 1191 1192 Create a directory named *pkg_dir* containing an ``__init__`` file with 1193 *init_source* as its contents. 1194 1195 1196.. function:: make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, \ 1197 source, depth=1, compiled=False) 1198 1199 Create a zip package directory with a path of *zip_dir* and *zip_basename* 1200 containing an empty ``__init__`` file and a file *script_basename* 1201 containing the *source*. If *compiled* is ``True``, both source files will 1202 be compiled and added to the zip package. Return a tuple of the full zip 1203 path and the archive name for the zip file. 1204 1205 1206:mod:`test.support.bytecode_helper` --- Support tools for testing correct bytecode generation 1207============================================================================================= 1208 1209.. module:: test.support.bytecode_helper 1210 :synopsis: Support tools for testing correct bytecode generation. 1211 1212The :mod:`test.support.bytecode_helper` module provides support for testing 1213and inspecting bytecode generation. 1214 1215.. versionadded:: 3.9 1216 1217The module defines the following class: 1218 1219.. class:: BytecodeTestCase(unittest.TestCase) 1220 1221 This class has custom assertion methods for inspecting bytecode. 1222 1223.. method:: BytecodeTestCase.get_disassembly_as_string(co) 1224 1225 Return the disassembly of *co* as string. 1226 1227 1228.. method:: BytecodeTestCase.assertInBytecode(x, opname, argval=_UNSPECIFIED) 1229 1230 Return instr if *opname* is found, otherwise throws :exc:`AssertionError`. 1231 1232 1233.. method:: BytecodeTestCase.assertNotInBytecode(x, opname, argval=_UNSPECIFIED) 1234 1235 Throws :exc:`AssertionError` if *opname* is found. 1236 1237 1238:mod:`test.support.threading_helper` --- Utilities for threading tests 1239====================================================================== 1240 1241.. module:: test.support.threading_helper 1242 :synopsis: Support for threading tests. 1243 1244The :mod:`test.support.threading_helper` module provides support for threading tests. 1245 1246.. versionadded:: 3.10 1247 1248 1249.. function:: join_thread(thread, timeout=None) 1250 1251 Join a *thread* within *timeout*. Raise an :exc:`AssertionError` if thread 1252 is still alive after *timeout* seconds. 1253 1254 1255.. decorator:: reap_threads 1256 1257 Decorator to ensure the threads are cleaned up even if the test fails. 1258 1259 1260.. function:: start_threads(threads, unlock=None) 1261 1262 Context manager to start *threads*, which is a sequence of threads. 1263 *unlock* is a function called after the threads are started, even if an 1264 exception was raised; an example would be :meth:`threading.Event.set`. 1265 ``start_threads`` will attempt to join the started threads upon exit. 1266 1267 1268.. function:: threading_cleanup(*original_values) 1269 1270 Cleanup up threads not specified in *original_values*. Designed to emit 1271 a warning if a test leaves running threads in the background. 1272 1273 1274.. function:: threading_setup() 1275 1276 Return current thread count and copy of dangling threads. 1277 1278 1279.. function:: wait_threads_exit(timeout=None) 1280 1281 Context manager to wait until all threads created in the ``with`` statement 1282 exit. 1283 1284 1285.. function:: catch_threading_exception() 1286 1287 Context manager catching :class:`threading.Thread` exception using 1288 :func:`threading.excepthook`. 1289 1290 Attributes set when an exception is caught: 1291 1292 * ``exc_type`` 1293 * ``exc_value`` 1294 * ``exc_traceback`` 1295 * ``thread`` 1296 1297 See :func:`threading.excepthook` documentation. 1298 1299 These attributes are deleted at the context manager exit. 1300 1301 Usage:: 1302 1303 with threading_helper.catch_threading_exception() as cm: 1304 # code spawning a thread which raises an exception 1305 ... 1306 1307 # check the thread exception, use cm attributes: 1308 # exc_type, exc_value, exc_traceback, thread 1309 ... 1310 1311 # exc_type, exc_value, exc_traceback, thread attributes of cm no longer 1312 # exists at this point 1313 # (to avoid reference cycles) 1314 1315 .. versionadded:: 3.8 1316 1317 1318:mod:`test.support.os_helper` --- Utilities for os tests 1319======================================================================== 1320 1321.. module:: test.support.os_helper 1322 :synopsis: Support for os tests. 1323 1324The :mod:`test.support.os_helper` module provides support for os tests. 1325 1326.. versionadded:: 3.10 1327 1328 1329.. data:: FS_NONASCII 1330 1331 A non-ASCII character encodable by :func:`os.fsencode`. 1332 1333 1334.. data:: SAVEDCWD 1335 1336 Set to :func:`os.getcwd`. 1337 1338 1339.. data:: TESTFN 1340 1341 Set to a name that is safe to use as the name of a temporary file. Any 1342 temporary file that is created should be closed and unlinked (removed). 1343 1344 1345.. data:: TESTFN_NONASCII 1346 1347 Set to a filename containing the :data:`FS_NONASCII` character, if it exists. 1348 This guarantees that if the filename exists, it can be encoded and decoded 1349 with the default filesystem encoding. This allows tests that require a 1350 non-ASCII filename to be easily skipped on platforms where they can't work. 1351 1352 1353.. data:: TESTFN_UNENCODABLE 1354 1355 Set to a filename (str type) that should not be able to be encoded by file 1356 system encoding in strict mode. It may be ``None`` if it's not possible to 1357 generate such a filename. 1358 1359 1360.. data:: TESTFN_UNDECODABLE 1361 1362 Set to a filename (bytes type) that should not be able to be decoded by 1363 file system encoding in strict mode. It may be ``None`` if it's not 1364 possible to generate such a filename. 1365 1366 1367.. data:: TESTFN_UNICODE 1368 1369 Set to a non-ASCII name for a temporary file. 1370 1371 1372.. class:: EnvironmentVarGuard() 1373 1374 Class used to temporarily set or unset environment variables. Instances can 1375 be used as a context manager and have a complete dictionary interface for 1376 querying/modifying the underlying ``os.environ``. After exit from the 1377 context manager all changes to environment variables done through this 1378 instance will be rolled back. 1379 1380 .. versionchanged:: 3.1 1381 Added dictionary interface. 1382 1383 1384.. class:: FakePath(path) 1385 1386 Simple :term:`path-like object`. It implements the :meth:`__fspath__` 1387 method which just returns the *path* argument. If *path* is an exception, 1388 it will be raised in :meth:`!__fspath__`. 1389 1390 1391.. method:: EnvironmentVarGuard.set(envvar, value) 1392 1393 Temporarily set the environment variable ``envvar`` to the value of 1394 ``value``. 1395 1396 1397.. method:: EnvironmentVarGuard.unset(envvar) 1398 1399 Temporarily unset the environment variable ``envvar``. 1400 1401 1402.. function:: can_symlink() 1403 1404 Return ``True`` if the OS supports symbolic links, ``False`` 1405 otherwise. 1406 1407 1408.. function:: can_xattr() 1409 1410 Return ``True`` if the OS supports xattr, ``False`` 1411 otherwise. 1412 1413 1414.. function:: change_cwd(path, quiet=False) 1415 1416 A context manager that temporarily changes the current working 1417 directory to *path* and yields the directory. 1418 1419 If *quiet* is ``False``, the context manager raises an exception 1420 on error. Otherwise, it issues only a warning and keeps the current 1421 working directory the same. 1422 1423 1424.. function:: create_empty_file(filename) 1425 1426 Create an empty file with *filename*. If it already exists, truncate it. 1427 1428 1429.. function:: fd_count() 1430 1431 Count the number of open file descriptors. 1432 1433 1434.. function:: fs_is_case_insensitive(directory) 1435 1436 Return ``True`` if the file system for *directory* is case-insensitive. 1437 1438 1439.. function:: make_bad_fd() 1440 1441 Create an invalid file descriptor by opening and closing a temporary file, 1442 and returning its descriptor. 1443 1444 1445.. function:: rmdir(filename) 1446 1447 Call :func:`os.rmdir` on *filename*. On Windows platforms, this is 1448 wrapped with a wait loop that checks for the existence of the file, 1449 which is needed due to antivirus programs that can hold files open and prevent 1450 deletion. 1451 1452 1453.. function:: rmtree(path) 1454 1455 Call :func:`shutil.rmtree` on *path* or call :func:`os.lstat` and 1456 :func:`os.rmdir` to remove a path and its contents. As with :func:`rmdir`, 1457 on Windows platforms 1458 this is wrapped with a wait loop that checks for the existence of the files. 1459 1460 1461.. decorator:: skip_unless_symlink 1462 1463 A decorator for running tests that require support for symbolic links. 1464 1465 1466.. decorator:: skip_unless_xattr 1467 1468 A decorator for running tests that require support for xattr. 1469 1470 1471.. function:: temp_cwd(name='tempcwd', quiet=False) 1472 1473 A context manager that temporarily creates a new directory and 1474 changes the current working directory (CWD). 1475 1476 The context manager creates a temporary directory in the current 1477 directory with name *name* before temporarily changing the current 1478 working directory. If *name* is ``None``, the temporary directory is 1479 created using :func:`tempfile.mkdtemp`. 1480 1481 If *quiet* is ``False`` and it is not possible to create or change 1482 the CWD, an error is raised. Otherwise, only a warning is raised 1483 and the original CWD is used. 1484 1485 1486.. function:: temp_dir(path=None, quiet=False) 1487 1488 A context manager that creates a temporary directory at *path* and 1489 yields the directory. 1490 1491 If *path* is ``None``, the temporary directory is created using 1492 :func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager 1493 raises an exception on error. Otherwise, if *path* is specified and 1494 cannot be created, only a warning is issued. 1495 1496 1497.. function:: temp_umask(umask) 1498 1499 A context manager that temporarily sets the process umask. 1500 1501 1502.. function:: unlink(filename) 1503 1504 Call :func:`os.unlink` on *filename*. As with :func:`rmdir`, 1505 on Windows platforms, this is 1506 wrapped with a wait loop that checks for the existence of the file. 1507 1508 1509:mod:`test.support.import_helper` --- Utilities for import tests 1510================================================================ 1511 1512.. module:: test.support.import_helper 1513 :synopsis: Support for import tests. 1514 1515The :mod:`test.support.import_helper` module provides support for import tests. 1516 1517.. versionadded:: 3.10 1518 1519 1520.. function:: forget(module_name) 1521 1522 Remove the module named *module_name* from ``sys.modules`` and delete any 1523 byte-compiled files of the module. 1524 1525 1526.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False) 1527 1528 This function imports and returns a fresh copy of the named Python module 1529 by removing the named module from ``sys.modules`` before doing the import. 1530 Note that unlike :func:`reload`, the original module is not affected by 1531 this operation. 1532 1533 *fresh* is an iterable of additional module names that are also removed 1534 from the ``sys.modules`` cache before doing the import. 1535 1536 *blocked* is an iterable of module names that are replaced with ``None`` 1537 in the module cache during the import to ensure that attempts to import 1538 them raise :exc:`ImportError`. 1539 1540 The named module and any modules named in the *fresh* and *blocked* 1541 parameters are saved before starting the import and then reinserted into 1542 ``sys.modules`` when the fresh import is complete. 1543 1544 Module and package deprecation messages are suppressed during this import 1545 if *deprecated* is ``True``. 1546 1547 This function will raise :exc:`ImportError` if the named module cannot be 1548 imported. 1549 1550 Example use:: 1551 1552 # Get copies of the warnings module for testing without affecting the 1553 # version being used by the rest of the test suite. One copy uses the 1554 # C implementation, the other is forced to use the pure Python fallback 1555 # implementation 1556 py_warnings = import_fresh_module('warnings', blocked=['_warnings']) 1557 c_warnings = import_fresh_module('warnings', fresh=['_warnings']) 1558 1559 .. versionadded:: 3.1 1560 1561 1562.. function:: import_module(name, deprecated=False, *, required_on=()) 1563 1564 This function imports and returns the named module. Unlike a normal 1565 import, this function raises :exc:`unittest.SkipTest` if the module 1566 cannot be imported. 1567 1568 Module and package deprecation messages are suppressed during this import 1569 if *deprecated* is ``True``. If a module is required on a platform but 1570 optional for others, set *required_on* to an iterable of platform prefixes 1571 which will be compared against :data:`sys.platform`. 1572 1573 .. versionadded:: 3.1 1574 1575 1576.. function:: modules_setup() 1577 1578 Return a copy of :data:`sys.modules`. 1579 1580 1581.. function:: modules_cleanup(oldmodules) 1582 1583 Remove modules except for *oldmodules* and ``encodings`` in order to 1584 preserve internal cache. 1585 1586 1587.. function:: unload(name) 1588 1589 Delete *name* from ``sys.modules``. 1590 1591 1592.. function:: make_legacy_pyc(source) 1593 1594 Move a :pep:`3147`/:pep:`488` pyc file to its legacy pyc location and return the file 1595 system path to the legacy pyc file. The *source* value is the file system 1596 path to the source file. It does not need to exist, however the PEP 1597 3147/488 pyc file must exist. 1598 1599 1600.. class:: CleanImport(*module_names) 1601 1602 A context manager to force import to return a new module reference. This 1603 is useful for testing module-level behaviors, such as the emission of a 1604 :exc:`DeprecationWarning` on import. Example usage:: 1605 1606 with CleanImport('foo'): 1607 importlib.import_module('foo') # New reference. 1608 1609 1610.. class:: DirsOnSysPath(*paths) 1611 1612 A context manager to temporarily add directories to :data:`sys.path`. 1613 1614 This makes a copy of :data:`sys.path`, appends any directories given 1615 as positional arguments, then reverts :data:`sys.path` to the copied 1616 settings when the context ends. 1617 1618 Note that *all* :data:`sys.path` modifications in the body of the 1619 context manager, including replacement of the object, 1620 will be reverted at the end of the block. 1621 1622 1623:mod:`test.support.warnings_helper` --- Utilities for warnings tests 1624==================================================================== 1625 1626.. module:: test.support.warnings_helper 1627 :synopsis: Support for warnings tests. 1628 1629The :mod:`test.support.warnings_helper` module provides support for warnings tests. 1630 1631.. versionadded:: 3.10 1632 1633 1634.. function:: ignore_warnings(*, category) 1635 1636 Suppress warnings that are instances of *category*, 1637 which must be :exc:`Warning` or a subclass. 1638 Roughly equivalent to :func:`warnings.catch_warnings` 1639 with :meth:`warnings.simplefilter('ignore', category=category) <warnings.simplefilter>`. 1640 For example:: 1641 1642 @warning_helper.ignore_warnings(category=DeprecationWarning) 1643 def test_suppress_warning(): 1644 # do something 1645 1646 .. versionadded:: 3.8 1647 1648 1649.. function:: check_no_resource_warning(testcase) 1650 1651 Context manager to check that no :exc:`ResourceWarning` was raised. You 1652 must remove the object which may emit :exc:`ResourceWarning` before the 1653 end of the context manager. 1654 1655 1656.. function:: check_syntax_warning(testcase, statement, errtext='', *, lineno=1, offset=None) 1657 1658 Test for syntax warning in *statement* by attempting to compile *statement*. 1659 Test also that the :exc:`SyntaxWarning` is emitted only once, and that it 1660 will be converted to a :exc:`SyntaxError` when turned into error. 1661 *testcase* is the :mod:`unittest` instance for the test. *errtext* is the 1662 regular expression which should match the string representation of the 1663 emitted :exc:`SyntaxWarning` and raised :exc:`SyntaxError`. If *lineno* 1664 is not ``None``, compares to the line of the warning and exception. 1665 If *offset* is not ``None``, compares to the offset of the exception. 1666 1667 .. versionadded:: 3.8 1668 1669 1670.. function:: check_warnings(*filters, quiet=True) 1671 1672 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it 1673 easier to test that a warning was correctly raised. It is approximately 1674 equivalent to calling ``warnings.catch_warnings(record=True)`` with 1675 :meth:`warnings.simplefilter` set to ``always`` and with the option to 1676 automatically validate the results that are recorded. 1677 1678 ``check_warnings`` accepts 2-tuples of the form ``("message regexp", 1679 WarningCategory)`` as positional arguments. If one or more *filters* are 1680 provided, or if the optional keyword argument *quiet* is ``False``, 1681 it checks to make sure the warnings are as expected: each specified filter 1682 must match at least one of the warnings raised by the enclosed code or the 1683 test fails, and if any warnings are raised that do not match any of the 1684 specified filters the test fails. To disable the first of these checks, 1685 set *quiet* to ``True``. 1686 1687 If no arguments are specified, it defaults to:: 1688 1689 check_warnings(("", Warning), quiet=True) 1690 1691 In this case all warnings are caught and no errors are raised. 1692 1693 On entry to the context manager, a :class:`WarningRecorder` instance is 1694 returned. The underlying warnings list from 1695 :func:`~warnings.catch_warnings` is available via the recorder object's 1696 :attr:`warnings` attribute. As a convenience, the attributes of the object 1697 representing the most recent warning can also be accessed directly through 1698 the recorder object (see example below). If no warning has been raised, 1699 then any of the attributes that would otherwise be expected on an object 1700 representing a warning will return ``None``. 1701 1702 The recorder object also has a :meth:`reset` method, which clears the 1703 warnings list. 1704 1705 The context manager is designed to be used like this:: 1706 1707 with check_warnings(("assertion is always true", SyntaxWarning), 1708 ("", UserWarning)): 1709 exec('assert(False, "Hey!")') 1710 warnings.warn(UserWarning("Hide me!")) 1711 1712 In this case if either warning was not raised, or some other warning was 1713 raised, :func:`check_warnings` would raise an error. 1714 1715 When a test needs to look more deeply into the warnings, rather than 1716 just checking whether or not they occurred, code like this can be used:: 1717 1718 with check_warnings(quiet=True) as w: 1719 warnings.warn("foo") 1720 assert str(w.args[0]) == "foo" 1721 warnings.warn("bar") 1722 assert str(w.args[0]) == "bar" 1723 assert str(w.warnings[0].args[0]) == "foo" 1724 assert str(w.warnings[1].args[0]) == "bar" 1725 w.reset() 1726 assert len(w.warnings) == 0 1727 1728 1729 Here all warnings will be caught, and the test code tests the captured 1730 warnings directly. 1731 1732 .. versionchanged:: 3.2 1733 New optional arguments *filters* and *quiet*. 1734 1735 1736.. class:: WarningsRecorder() 1737 1738 Class used to record warnings for unit tests. See documentation of 1739 :func:`check_warnings` above for more details. 1740