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