test --- Python 的回歸測試 (regression tests) 套件

備註

The test package is meant for internal use by Python only. It is documented for the benefit of the core developers of Python. Any use of this package outside of Python's standard library is discouraged as code mentioned here can change or be removed without notice between releases of Python.


The test package contains all regression tests for Python as well as the modules test.support and test.regrtest. test.support is used to enhance your tests while test.regrtest drives the testing suite.

Each module in the test package whose name starts with test_ is a testing suite for a specific module or feature. All new tests should be written using the unittest or doctest module. Some older tests are written using a "traditional" testing style that compares output printed to sys.stdout; this style of test is considered deprecated.

也參考

unittest 模組

撰寫 PyUnit 回歸測試。

doctest 模組

鑲嵌在文件字串中的測試。

撰寫 test 套件的單元測試

It is preferred that tests that use the unittest module follow a few guidelines. One is to name the test module by starting it with test_ and end it with the name of the module being tested. The test methods in the test module should start with test_ and end with a description of what the method is testing. This is needed so that the methods are recognized by the test driver as test methods. Also, no documentation string for the method should be included. A comment (such as # Tests function returns only True or False) should be used to provide documentation for test methods. This is done because documentation strings get printed out if they exist and thus what test is being run is not stated.

A basic boilerplate is often used:

import unittest
from test import support

class MyTestCase1(unittest.TestCase):

    # Only use setUp() and tearDown() if necessary

    def setUp(self):
        ... code to execute in preparation for tests ...

    def tearDown(self):
        ... code to execute to clean up after tests ...

    def test_feature_one(self):
        # Test feature one.
        ... testing code ...

    def test_feature_two(self):
        # Test feature two.
        ... testing code ...

    ... more test methods ...

class MyTestCase2(unittest.TestCase):
    ... same structure as MyTestCase1 ...

... more test classes ...

if __name__ == '__main__':
    unittest.main()

This code pattern allows the testing suite to be run by test.regrtest, on its own as a script that supports the unittest CLI, or via the python -m unittest CLI.

The goal for regression testing is to try to break code. This leads to a few guidelines to be followed:

  • The testing suite should exercise all classes, functions, and constants. This includes not just the external API that is to be presented to the outside world but also "private" code.

  • Whitebox testing (examining the code being tested when the tests are being written) is preferred. Blackbox testing (testing only the published user interface) is not complete enough to make sure all boundary and edge cases are tested.

  • Make sure all possible values are tested including invalid ones. This makes sure that not only all valid values are acceptable but also that improper values are handled correctly.

  • Exhaust as many code paths as possible. Test where branching occurs and thus tailor input to make sure as many different paths through the code are taken.

  • Add an explicit test for any bugs discovered for the tested code. This will make sure that the error does not crop up again if the code is changed in the future.

  • Make sure to clean up after your tests (such as close and remove all temporary files).

  • If a test is dependent on a specific condition of the operating system then verify the condition already exists before attempting the test.

  • Import as few modules as possible and do it as soon as possible. This minimizes external dependencies of tests and also minimizes possible anomalous behavior from side-effects of importing a module.

  • Try to maximize code reuse. On occasion, tests will vary by something as small as what type of input is used. Minimize code duplication by subclassing a basic test class with a class that specifies the input:

    class TestFuncAcceptsSequencesMixin:
    
        func = mySuperWhammyFunction
    
        def test_func(self):
            self.func(self.arg)
    
    class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
        arg = [1, 2, 3]
    
    class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
        arg = 'abc'
    
    class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
        arg = (1, 2, 3)
    

    When using this pattern, remember that all classes that inherit from unittest.TestCase are run as tests. The TestFuncAcceptsSequencesMixin class in the example above does not have any data and so can't be run by itself, thus it does not inherit from unittest.TestCase.

也參考

測試驅動開發

由 Kent Beck 所著,關於先寫測試再寫程式的書籍。

使用命令列介面執行測試

The test package can be run as a script to drive Python's regression test suite, thanks to the -m option: python -m test. Under the hood, it uses test.regrtest; the call python -m test.regrtest used in previous Python versions still works. Running the script by itself automatically starts running all regression tests in the test package. It does this by finding all modules in the package whose name starts with test_, importing them, and executing the function test_main() if present or loading the tests via unittest.TestLoader.loadTestsFromModule if test_main does not exist. The names of tests to execute may also be passed to the script. Specifying a single regression test (python -m test test_spam) will minimize output and only print whether the test passed or failed.

Running test directly allows what resources are available for tests to use to be set. You do this by using the -u command-line option. Specifying all as the value for the -u option enables all possible resources: python -m test -uall. If all but one resource is desired (a more common case), a comma-separated list of resources that are not desired may be listed after all. The command python -m test -uall,-audio,-largefile will run test with all resources except the audio and largefile resources. For a list of all resources and more command-line options, run python -m test -h.

Some other ways to execute the regression tests depend on what platform the tests are being executed on. On Unix, you can run make test at the top-level directory where Python was built. On Windows, executing rt.bat from your PCbuild directory will run all regression tests.

在 3.14 版被加入: Output is colorized by default and can be controlled using environment variables.

test.support --- Python 測試套件的工具

test.support 模組提供 Python 回歸測試套件的支援。

備註

test.support is not a public module. It is documented here to help Python developers write tests. The API of this module is subject to change without backwards compatibility concerns between releases.

此模組定義了以下例外:

exception test.support.TestFailed

Exception to be raised when a test fails. This is deprecated in favor of unittest-based tests and unittest.TestCase's assertion methods.

exception test.support.ResourceDenied

Subclass of unittest.SkipTest. Raised when a resource (such as a network connection) is not available. Raised by the requires() function.

test.support 模組定義了以下常數:

test.support.verbose

True when verbose output is enabled. Should be checked when more detailed information is desired about a running test. verbose is set by test.regrtest.

test.support.is_jython

如果執行的直譯器是 Jython,則為 True

test.support.is_android

如果 sys.platformandroid 則為 True

test.support.is_emscripten

如果 sys.platformemscripten 則為 True

test.support.is_wasi

如果 sys.platformwasi 則為 True

test.support.is_apple_mobile

如果 sys.platformiostvoswatchos 則為 True

test.support.is_apple

True if sys.platform is darwin or is_apple_mobile is True.

test.support.unix_shell

Path for shell if not on Windows; otherwise None.

test.support.LOOPBACK_TIMEOUT

Timeout in seconds for tests using a network server listening on the network local loopback interface like 127.0.0.1.

The timeout is long enough to prevent test failure: it takes into account that the client and the server can run in different threads or even different processes.

The timeout should be long enough for connect(), recv() and send() methods of socket.socket.

預設值為 5 秒。

另請參閱 INTERNET_TIMEOUT

test.support.INTERNET_TIMEOUT

Timeout in seconds for network requests going to the internet.

The timeout is short enough to prevent a test to wait for too long if the internet request is blocked for whatever reason.

Usually, a timeout using INTERNET_TIMEOUT should not mark a test as failed, but skip the test instead: see transient_internet().

預設值為 1 分鐘。

另請參閱 LOOPBACK_TIMEOUT

test.support.SHORT_TIMEOUT

Timeout in seconds to mark a test as failed if the test takes "too long".

The timeout value depends on the regrtest --timeout command line option.

If a test using SHORT_TIMEOUT starts to fail randomly on slow buildbots, use LONG_TIMEOUT instead.

預設值為 30 秒。

test.support.LONG_TIMEOUT

Timeout in seconds to detect when a test hangs.

It is long enough to reduce the risk of test failure on the slowest Python buildbots. It should not be used to mark a test as failed if the test takes "too long". The timeout value depends on the regrtest --timeout command line option.

預設值為 5 分鐘。

請參閱 LOOPBACK_TIMEOUTINTERNET_TIMEOUTSHORT_TIMEOUT

test.support.PGO

Set when tests can be skipped when they are not useful for PGO.

test.support.PIPE_MAX_SIZE

A constant that is likely larger than the underlying OS pipe buffer size, to make writes blocking.

test.support.Py_DEBUG

True if Python was built with the Py_DEBUG macro defined, that is, if Python was built in debug mode.

在 3.12 版被加入.

test.support.SOCK_MAX_SIZE

A constant that is likely larger than the underlying OS socket buffer size, to make writes blocking.

test.support.TEST_SUPPORT_DIR

設定為包含 test.support 的頂層目錄。

test.support.TEST_HOME_DIR

設定為測試套件的頂層目錄。

test.support.TEST_DATA_DIR

設定為測試套件中的 data 目錄。

test.support.MAX_Py_ssize_t

設定為 sys.maxsize 以進行大記憶體測試。

test.support.max_memuse

Set by set_memlimit() as the memory limit for big memory tests. Limited by MAX_Py_ssize_t.

test.support.real_max_memuse

Set by set_memlimit() as the memory limit for big memory tests. Not limited by MAX_Py_ssize_t.

test.support.MISSING_C_DOCSTRINGS

Set to True if Python is built without docstrings (the WITH_DOC_STRINGS macro is not defined). See the configure --without-doc-strings option.

另請參閱 HAVE_DOCSTRINGS 變數。

test.support.HAVE_DOCSTRINGS

Set to True if function docstrings are available. See the python -OO option, which strips docstrings of functions implemented in Python.

請參閱 MISSING_C_DOCSTRINGS 變數。

test.support.TEST_HTTP_URL

Define the URL of a dedicated HTTP server for the network tests.

test.support.ALWAYS_EQ

Object that is equal to anything. Used to test mixed type comparison.

test.support.NEVER_EQ

Object that is not equal to anything (even to ALWAYS_EQ). Used to test mixed type comparison.

test.support.LARGEST

Object that is greater than anything (except itself). Used to test mixed type comparison.

test.support.SMALLEST

Object that is less than anything (except itself). Used to test mixed type comparison.

test.support 模組定義了以下函式:

test.support.busy_retry(timeout, err_msg=None, /, *, error=True)

執行迴圈主體直到 break 停止迴圈。

After timeout seconds, raise an AssertionError if error is true, or just stop the loop if error is false.

範例:

for _ in support.busy_retry(support.SHORT_TIMEOUT):
    if check():
        break

error=False 用法範例:

for _ in support.busy_retry(support.SHORT_TIMEOUT, error=False):
    if check():
        break
else:
    raise RuntimeError('my custom error')
test.support.sleeping_retry(timeout, err_msg=None, /, *, init_delay=0.010, max_delay=1.0, error=True)

Wait strategy that applies exponential backoff.

Run the loop body until break stops the loop. Sleep at each loop iteration, but not at the first iteration. The sleep delay is doubled at each iteration (up to max_delay seconds).

請見 busy_retry() 文件以瞭解參數用法。

在 SHORT_TIMEOUT 秒後引發例外的範例:

for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
    if check():
        break

error=False 用法範例:

for _ in support.sleeping_retry(support.SHORT_TIMEOUT, error=False):
    if check():
        break
else:
    raise RuntimeError('my custom error')
test.support.is_resource_enabled(resource)

Return True if resource is enabled and available. The list of available resources is only set when test.regrtest is executing the tests.

test.support.get_resource_value(resource)

Return the value specified for resource (as -u resource=value). Return None if resource is disabled or no value is specified.

test.support.python_is_optimized()

如果 Python 不是使用 -O0-Og 建置則回傳 True

test.support.with_pymalloc()

回傳 _testcapi.WITH_PYMALLOC

test.support.requires(resource, msg=None)

Raise ResourceDenied if resource is not available. msg is the argument to ResourceDenied if it is raised. Always returns True if called by a function whose __name__ is '__main__'. Used when tests are executed by test.regrtest.

test.support.sortdict(dict)

Return a repr of dict with keys sorted.

test.support.findfile(filename, subdir=None)

Return the path to the file named filename. If no match is found filename is returned. This does not equal a failure since it could be the path to the file.

Setting subdir indicates a relative path to use to find the file rather than looking directly in the path directories.

test.support.get_pagesize()

Get size of a page in bytes.

在 3.12 版被加入.

test.support.setswitchinterval(interval)

Set the sys.setswitchinterval() to the given interval. Defines a minimum interval for Android systems to prevent the system from hanging.

test.support.check_impl_detail(**guards)

Use this check to guard CPython's implementation-specific tests or to run them only on the implementations guarded by the arguments. This function returns True or False depending on the host platform. Example usage:

check_impl_detail()               # Only on CPython (default).
check_impl_detail(jython=True)    # Only on Jython.
check_impl_detail(cpython=False)  # Everywhere except CPython.
test.support.set_memlimit(limit)

Set the values for max_memuse and real_max_memuse for big memory tests.

test.support.record_original_stdout(stdout)

Store the value from stdout. It is meant to hold the stdout at the time the regrtest began.

test.support.get_original_stdout()

Return the original stdout set by record_original_stdout() or sys.stdout if it's not set.

test.support.args_from_interpreter_flags()

Return a list of command line arguments reproducing the current settings in sys.flags and sys.warnoptions.

test.support.optim_args_from_interpreter_flags()

Return a list of command line arguments reproducing the current optimization settings in sys.flags.

test.support.captured_stdin()
test.support.captured_stdout()
test.support.captured_stderr()

A context managers that temporarily replaces the named stream with io.StringIO object.

使用輸出串流的範例:

with captured_stdout() as stdout, captured_stderr() as stderr:
    print("hello")
    print("error", file=sys.stderr)
assert stdout.getvalue() == "hello\n"
assert stderr.getvalue() == "error\n"

使用輸入串流的範例:

with captured_stdin() as stdin:
    stdin.write('hello\n')
    stdin.seek(0)
    # call test code that consumes from sys.stdin
    captured = input()
self.assertEqual(captured, "hello")
test.support.disable_faulthandler()

A context manager that temporary disables faulthandler.

test.support.gc_collect()

Force as many objects as possible to be collected. This is needed because timely deallocation is not guaranteed by the garbage collector. This means that __del__ methods may be called later than expected and weakrefs may remain alive for longer than expected.

test.support.disable_gc()

A context manager that disables the garbage collector on entry. On exit, the garbage collector is restored to its prior state.

test.support.swap_attr(obj, attr, new_val)

Context manager to swap out an attribute with a new object.

用法:

with swap_attr(obj, "attr", 5):
    ...

This will set obj.attr to 5 for the duration of the with block, restoring the old value at the end of the block. If attr doesn't exist on obj, it will be created and then deleted at the end of the block.

The old value (or None if it doesn't exist) will be assigned to the target of the "as" clause, if there is one.

test.support.swap_item(