開發工具
********

本章所描述的模組可以幫助你編寫軟體。例如 "pydoc" 模組可以根據模組的內
容生成文件；"doctest" 和 "unittest" 模組則包含編寫單元測試的框架，這些
測試程式碼會自動執行並驗證輸出結果是否正確。

本章節所描述的模組列表為：

* "typing" --- 支援型別提示

  * Python 型別系統的技術規範

  * 型別別名

  * NewType

  * 註釋 callable 物件

  * 泛型

  * 註釋元組 (tuple)

  * 類別物件的型別

  * Annotating generators and coroutines

  * 使用者定義泛型型別

  * "Any" 型別

  * 標稱 (nominal) 子型別 vs 結構子型別

  * 模組內容

    * 特別型別原語 (primitive)

      * 特別型別

        * "Any"

        * "AnyStr"

        * "LiteralString"

        * "Never"

        * "NoReturn"

        * "Self"

        * "TypeAlias"

      * 特別型式

        * "Union"

        * "Optional"

        * "Concatenate"

        * "Literal"

        * "ClassVar"

        * "Final"

        * "Required"

        * "NotRequired"

        * "ReadOnly"

        * "Annotated"

        * "TypeIs"

        * "TypeGuard"

        * "Unpack"

      * Building generic types and type aliases

        * "Generic"

        * "TypeVar"

          * "__name__"

          * "__covariant__"

          * "__contravariant__"

          * "__infer_variance__"

          * "__bound__"

          * "__constraints__"

          * "__default__"

          * "has_default()"

        * "TypeVarTuple"

          * "__name__"

          * "__default__"

          * "has_default()"

        * "ParamSpec"

          * "args"

          * "kwargs"

          * "__name__"

          * "__default__"

          * "has_default()"

        * "ParamSpecArgs"

        * "ParamSpecKwargs"

        * "TypeAliasType"

          * "__name__"

          * "__module__"

          * "__type_params__"

          * "__value__"

      * Other special directives

        * "NamedTuple"

        * "NewType"

          * "__module__"

          * "__name__"

          * "__supertype__"

        * "Protocol"

        * "runtime_checkable()"

        * "TypedDict"

          * "__total__"

          * "__required_keys__"

          * "__optional_keys__"

          * "__readonly_keys__"

          * "__mutable_keys__"

    * 協定

      * "SupportsAbs"

      * "SupportsBytes"

      * "SupportsComplex"

      * "SupportsFloat"

      * "SupportsIndex"

      * "SupportsInt"

      * "SupportsRound"

    * ABCs for working with IO

      * "IO"

      * "TextIO"

      * "BinaryIO"

    * 函式與裝飾器

      * "cast()"

      * "assert_type()"

      * "assert_never()"

      * "reveal_type()"

      * "dataclass_transform()"

      * "overload()"

      * "get_overloads()"

      * "clear_overloads()"

      * "final()"

      * "no_type_check()"

      * "no_type_check_decorator()"

      * "override()"

      * "type_check_only()"

    * Introspection helpers

      * "get_type_hints()"

      * "get_origin()"

      * "get_args()"

      * "get_protocol_members()"

      * "is_protocol()"

      * "is_typeddict()"

      * "ForwardRef"

      * "NoDefault"

    * 常數

      * "TYPE_CHECKING"

    * 棄用的別名

      * 內建型別的別名

        * "Dict"

        * "List"

        * "Set"

        * "FrozenSet"

        * "Tuple"

        * "Type"

      * "collections" 中型別的別名

        * "DefaultDict"

        * "OrderedDict"

        * "ChainMap"

        * "Counter"

        * "Deque"

      * Aliases to other concrete types

        * "Pattern"

        * "Match"

        * "Text"

      * "collections.abc" 中容器 ABC 的別名

        * "AbstractSet"

        * "ByteString"

        * "Collection"

        * "Container"

        * "ItemsView"

        * "KeysView"

        * "Mapping"

        * "MappingView"

        * "MutableMapping"

        * "MutableSequence"

        * "MutableSet"

        * "Sequence"

        * "ValuesView"

      * Aliases to asynchronous ABCs in "collections.abc"

        * "Coroutine"

        * "AsyncGenerator"

        * "AsyncIterable"

        * "AsyncIterator"

        * "Awaitable"

      * Aliases to other ABCs in "collections.abc"

        * "Iterable"

        * "Iterator"

        * "Callable"

        * "Generator"

        * "Hashable"

        * "Reversible"

        * "Sized"

      * "contextlib" ABC 的別名

        * "ContextManager"

        * "AsyncContextManager"

  * Deprecation Timeline of Major Features

* "pydoc" --- 文件產生器與線上幫助系統

* Python 開發模式

  * Python 開發模式的影響

  * ResourceWarning 範例

  * 檔案描述器的錯誤範例

* "doctest" --- 測試互動式 Python 範例

  * Simple Usage: Checking Examples in Docstrings

  * Simple Usage: Checking Examples in a Text File

  * How It Works

    * Which Docstrings Are Examined?

    * How are Docstring Examples Recognized?

    * What's the Execution Context?

    * What About Exceptions?

    * 可選旗標

      * "DONT_ACCEPT_TRUE_FOR_1"

      * "DONT_ACCEPT_BLANKLINE"

      * "NORMALIZE_WHITESPACE"

      * "ELLIPSIS"

      * "IGNORE_EXCEPTION_DETAIL"

      * "SKIP"

      * "COMPARISON_FLAGS"

      * "REPORT_UDIFF"

      * "REPORT_CDIFF"

      * "REPORT_NDIFF"

      * "REPORT_ONLY_FIRST_FAILURE"

      * "FAIL_FAST"

      * "REPORTING_FLAGS"

      * "register_optionflag()"

    * Directives

    * 警告

  * 基礎 API

    * "testfile()"

    * "testmod()"

    * "run_docstring_examples()"

  * Unittest API

    * "DocFileSuite()"

    * "DocTestSuite()"

    * "failureException"

    * "set_unittest_reportflags()"

  * Advanced API

    * DocTest 物件

      * "DocTest"

        * "examples"

        * "globs"

        * "name"

        * "filename"

        * "lineno"

        * "docstring"

    * Example 物件

      * "Example"

        * "source"

        * "want"

        * "exc_msg"

        * "lineno"

        * "indent"

        * "options"

    * DocTestFinder 物件

      * "DocTestFinder"

        * "find()"

    * DocTestParser 物件

      * "DocTestParser"

        * "get_doctest()"

        * "get_examples()"

        * "parse()"

    * TestResults objects

      * "TestResults"

        * "failed"

        * "attempted"

        * "skipped"

    * DocTestRunner 物件

      * "DocTestRunner"

        * "report_start()"

        * "report_success()"

        * "report_failure()"

        * "report_unexpected_exception()"

        * "run()"

        * "summarize()"

        * "tries"

        * "failures"

        * "skips"

    * OutputChecker 物件

      * "OutputChecker"

        * "check_output()"

        * "output_difference()"

  * Debugging

    * "script_from_examples()"

    * "testsource()"

    * "debug()"

    * "debug_src()"

    * "DebugRunner"

    * "DocTestFailure"

    * "test"

    * "example"

    * "got"

    * "UnexpectedException"

    * "test"

    * "example"

    * "exc_info"

  * Soapbox

* "unittest" --- 單元測試框架

  * 簡單範例

  * 命令執行列介面 (Command-Line Interface)

    * 命令列模式選項

  * Test Discovery（測試探索）

  * Organizing test code

  * Re-using old test code

  * Skipping tests and expected failures

    * "skip()"

    * "skipIf()"

    * "skipUnless()"

    * "expectedFailure()"

    * "SkipTest"

  * Distinguishing test iterations using subtests

  * Classes and functions

    * Test cases

      * "TestCase"

        * "setUp()"

        * "tearDown()"

        * "setUpClass()"

        * "tearDownClass()"

        * "run()"

        * "skipTest()"

        * "subTest()"

        * "debug()"

        * "assertEqual()"

        * "assertNotEqual()"

        * "assertTrue()"

        * "assertFalse()"

        * "assertIs()"

        * "assertIsNot()"

        * "assertIsNone()"

        * "assertIsNotNone()"

        * "assertIn()"

        * "assertNotIn()"

        * "assertIsInstance()"

        * "assertNotIsInstance()"

        * "assertRaises()"

        * "assertRaisesRegex()"

        * "assertWarns()"

        * "assertWarnsRegex()"

        * "assertLogs()"

          * "records"

          * "output"

        * "assertNoLogs()"

        * "assertAlmostEqual()"

        * "assertNotAlmostEqual()"

        * "assertGreater()"

        * "assertGreaterEqual()"

        * "assertLess()"

        * "assertLessEqual()"

        * "assertRegex()"

        * "assertNotRegex()"

        * "assertCountEqual()"

        * "addTypeEqualityFunc()"

        * "assertMultiLineEqual()"

        * "assertSequenceEqual()"

        * "assertListEqual()"

        * "assertTupleEqual()"

        * "assertSetEqual()"

        * "assertDictEqual()"

        * "fail()"

        * "failureException"

        * "longMessage"

        * "maxDiff"

        * "countTestCases()"

        * "defaultTestResult()"

        * "id()"

        * "shortDescription()"

        * "addCleanup()"

        * "enterContext()"

        * "doCleanups()"

        * "addClassCleanup()"

        * "enterClassContext()"

        * "doClassCleanups()"

      * "IsolatedAsyncioTestCase"

        * "loop_factory"

        * "asyncSetUp()"

        * "asyncTearDown()"

        * "addAsyncCleanup()"

        * "enterAsyncContext()"

        * "run()"

      * "FunctionTestCase"

    * Grouping tests

      * "TestSuite"

        * "addTest()"

        * "addTests()"

        * "run()"

        * "debug()"

        * "countTestCases()"

        * "__iter__()"

    * Loading and running tests

      * "TestLoader"

        * "errors"

        * "loadTestsFromTestCase()"

        * "loadTestsFromModule()"

        * "loadTestsFromName()"

        * "loadTestsFromNames()"

        * "getTestCaseNames()"

        * "discover()"

        * "testMethodPrefix"

        * "sortTestMethodsUsing"

        * "suiteClass"

        * "testNamePatterns"

      * "TestResult"

        * "errors"

        * "failures"

        * "skipped"

        * "expectedFailures"

        * "unexpectedSuccesses"

        * "collectedDurations"

        * "shouldStop"

        * "testsRun"

        * "buffer"

        * "failfast"

        * "tb_locals"

        * "wasSuccessful()"

        * "stop()"

        * "startTest()"

        * "stopTest()"

        * "startTestRun()"

        * "stopTestRun()"

        * "addError()"

        * "addFailure()"

        * "addSuccess()"

        * "addSkip()"

        * "addExpectedFailure()"

        * "addUnexpectedSuccess()"

        * "addSubTest()"

        * "addDuration()"

      * "TextTestResult"

      * "defaultTestLoader"

      * "TextTestRunner"

        * "_makeResult()"

        * "run()"

      * "main()"

      * load_tests Protocol

  * Class and Module Fixtures

    * setUpClass and tearDownClass

    * setUpModule and tearDownModule

      * "addModuleCleanup()"

      * "enterModuleContext()"

      * "doModuleCleanups()"

  * Signal Handling

    * "installHandler()"

    * "registerResult()"

    * "removeResult()"

    * "removeHandler()"

* "unittest.mock" — mock 物件函式庫

  * 快速導引

  * Mock 類別

    * "Mock"

      * "assert_called()"

      * "assert_called_once()"

      * "assert_called_with()"

      * "assert_called_once_with()"

      * "assert_any_call()"

      * "assert_has_calls()"

      * "assert_not_called()"

      * "reset_mock()"

      * "mock_add_spec()"

      * "attach_mock()"

      * "configure_mock()"

      * "__dir__()"

      * "_get_child_mock()"

      * "called"

      * "call_count"

      * "return_value"

      * "side_effect"

      * "call_args"

      * "call_args_list"

      * "method_calls"

      * "mock_calls"

      * "__class__"

    * "NonCallableMock"

    * "PropertyMock"

    * "AsyncMock"

      * "assert_awaited()"

      * "assert_awaited_once()"

      * "assert_awaited_with()"

      * "assert_awaited_once_with()"

      * "assert_any_await()"

      * "assert_has_awaits()"

      * "assert_not_awaited()"

      * "reset_mock()"

      * "await_count"

      * "await_args"

      * "await_args_list"

    * "ThreadingMock"

      * "wait_until_called()"

      * "wait_until_any_call_with()"

      * "DEFAULT_TIMEOUT"

    * 呼叫

    * 刪除屬性

    * Mock 名稱與名稱屬性

    * 如同屬性一般附加 mock

  * Patchers

    * patch

      * "patch()"

    * patch.object

      * "object()"

    * patch.dict

      * "dict()"

    * patch.multiple

      * "multiple()"

    * patch 方法：啟動與停止

      * "stopall()"

    * patch 內建函式

    * TEST_PREFIX

    * 巢狀使用 Patch 裝飾器

    * 該 patch 何處

    * Patch 描述器與代理物件 (Proxy Objects)

  * MagicMock 以及魔術方法支援

    * Mock 魔術方法

    * Magic Mock

      * "MagicMock"

      * "NonCallableMagicMock"

  * 輔助函式

    * sentinel（哨兵）

      * "sentinel"

    * DEFAULT

      * "DEFAULT"

    * call

      * "call()"

      * "call_list()"

    * create_autospec

      * "create_autospec()"

    * ANY

      * "ANY"

    * FILTER_DIR

      * "FILTER_DIR"

    * mock_open

      * "mock_open()"

    * Autospeccing（自動規格）

    * 密封 mock

      * "seal()"

  * "side_effect"、"return_value" 和 *wraps* 的優先順序

* "unittest.mock" --- 入門指南

  * 使用 Mock 的方式

    * 使用 Mock 來 patching 方法

    * 對物件的方法呼叫使用 mock

    * Mock 類別

    * 命名你的 mock

    * 追蹤所有呼叫

    * 設定回傳值和屬性

    * 透過 mock 引發例外

    * Side effect 函式以及可疊代物件

    * Mock 非同步可疊代物件

    * Mock 非同步情境管理器

    * 從現有物件建立 mock

    * 使用 side_effect 回傳各別檔案內容

  * Patch 裝飾器

  * 更多範例

    * Mock 鍊接呼叫

    * 部分 mocking

    * Mock 產生器方法

    * 對每個測試方法應用相同的 patch

    * Mock Unbound Methods （未繫結方法）

    * 使用 mock 檢查多個呼叫

    * 應對可變引數

    * 巢狀使用 Patch

    * 使用 MagicMock 來 mock 字典

    * Mock 子類別及其屬性

    * 使用 patch.dict 來 mock import

    * 追蹤呼叫順序與更簡潔的呼叫斷言

    * 更複雜的引數匹配

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

  * 撰寫 "test" 套件的單元測試

  * 使用命令列介面執行測試

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

  * "TestFailed"

  * "ResourceDenied"

  * "verbose"

  * "is_jython"

  * "is_android"

  * "unix_shell"

  * "LOOPBACK_TIMEOUT"

  * "INTERNET_TIMEOUT"

  * "SHORT_TIMEOUT"

  * "LONG_TIMEOUT"

  * "PGO"

  * "PIPE_MAX_SIZE"

  * "Py_DEBUG"

  * "SOCK_MAX_SIZE"

  * "TEST_SUPPORT_DIR"

  * "TEST_HOME_DIR"

  * "TEST_DATA_DIR"

  * "MAX_Py_ssize_t"

  * "max_memuse"

  * "real_max_memuse"

  * "MISSING_C_DOCSTRINGS"

  * "HAVE_DOCSTRINGS"

  * "TEST_HTTP_URL"

  * "ALWAYS_EQ"

  * "NEVER_EQ"

  * "LARGEST"

  * "SMALLEST"

  * "busy_retry()"

  * "sleeping_retry()"

  * "is_resource_enabled()"

  * "python_is_optimized()"

  * "with_pymalloc()"

  * "requires()"

  * "sortdict()"

  * "findfile()"

  * "get_pagesize()"

  * "setswitchinterval()"

  * "check_impl_detail()"

  * "set_memlimit()"

  * "record_original_stdout()"

  * "get_original_stdout()"

  * "args_from_interpreter_flags()"

  * "optim_args_from_interpreter_flags()"

  * "captured_stdin()"

  * "captured_stdout()"

  * "captured_stderr()"

  * "disable_faulthandler()"

  * "gc_collect()"

  * "disable_gc()"

  * "swap_attr()"

  * "swap_item()"

  * "flush_std_streams()"

  * "print_warning()"

  * "wait_process()"

  * "calcobjsize()"

  * "calcvobjsize()"

  * "checksizeof()"

  * "anticipate_failure()"

  * "system_must_validate_cert()"

  * "run_with_locale()"

  * "run_with_tz()"

  * "requires_freebsd_version()"

  * "requires_linux_version()"

  * "requires_mac_version()"

  * "requires_gil_enabled()"

  * "requires_IEEE_754()"

  * "requires_zlib()"

  * "requires_gzip()"

  * "requires_bz2()"

  * "requires_lzma()"

  * "requires_resource()"

  * "requires_docstrings()"

  * "requires_limited_api()"

  * "cpython_only()"

  * "impl_detail()"

  * "no_tracing()"

  * "refcount_test()"

  * "bigmemtest()"

  * "bigaddrspacetest()"

  * "check_syntax_error()"

  * "open_urlresource()"

  * "reap_children()"

  * "get_attribute()"

  * "catch_unraisable_exception()"

  * "load_package_tests()"

  * "detect_api_mismatch()"

  * "patch()"

  * "run_in_subinterp()"

  * "check_free_after_iterating()"

  * "missing_compiler_executable()"

  * "check__all__()"

  * "skip_if_broken_multiprocessing_synchronize()"

  * "check_disallow_instantiation()"

  * "adjust_int_max_str_digits()"

  * "SuppressCrashReport"

  * "SaveSignals"

    * "save()"

    * "restore()"

  * "Matcher"

    * "matches()"

    * "match_value()"

* "test.support.socket_helper" --- 用於 socket 測試的工具

  * "IPV6_ENABLED"

  * "find_unused_port()"

  * "bind_port()"

  * "bind_unix_socket()"

  * "skip_unless_bind_unix_socket()"

  * "transient_internet()"

* "test.support.script_helper" --- 用於 Python 執行測試的工具

  * "interpreter_requires_environment()"

  * "run_python_until_end()"

  * "assert_python_ok()"

  * "assert_python_failure()"

  * "spawn_python()"

  * "kill_python()"

  * "make_script()"

  * "make_zip_script()"

  * "make_pkg()"

  * "make_zip_pkg()"

* "test.support.bytecode_helper" --- 用於測試位元組碼能正確產生的支援
  工具

  * "BytecodeTestCase"

  * "get_disassembly_as_string()"

  * "assertInBytecode()"

  * "assertNotInBytecode()"

* "test.support.threading_helper" --- Utilities for threading tests

  * "join_thread()"

  * "reap_threads()"

  * "start_threads()"

  * "threading_cleanup()"

  * "threading_setup()"

  * "wait_threads_exit()"

  * "catch_threading_exception()"

* "test.support.os_helper" --- 用於 os 測試的工具

  * "FS_NONASCII"

  * "SAVEDCWD"

  * "TESTFN"

  * "TESTFN_NONASCII"

  * "TESTFN_UNENCODABLE"

  * "TESTFN_UNDECODABLE"

  * "TESTFN_UNICODE"

  * "EnvironmentVarGuard"

  * "FakePath"

  * "set()"

  * "unset()"

  * "can_symlink()"

  * "can_xattr()"

  * "change_cwd()"

  * "create_empty_file()"

  * "fd_count()"

  * "fs_is_case_insensitive()"

  * "make_bad_fd()"

  * "rmdir()"

  * "rmtree()"

  * "skip_unless_symlink()"

  * "skip_unless_xattr()"

  * "temp_cwd()"

  * "temp_dir()"

  * "temp_umask()"

  * "unlink()"

* "test.support.import_helper" --- 用於 import 測試的工具

  * "forget()"

  * "import_fresh_module()"

  * "import_module()"

  * "modules_setup()"

  * "modules_cleanup()"

  * "unload()"

  * "make_legacy_pyc()"

  * "CleanImport"

  * "DirsOnSysPath"

* "test.support.warnings_helper" --- 用於 warnings 測試的工具

  * "ignore_warnings()"

  * "check_no_resource_warning()"

  * "check_syntax_warning()"

  * "check_warnings()"

  * "WarningsRecorder"
