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