Development Tools¶
The modules described in this chapter help you write software. For example, the
pydoc module takes a module and generates documentation based on the
module’s contents. The doctest and unittest modules contains
frameworks for writing unit tests that automatically exercise code and verify
that the expected output is produced.
The list of modules described in this chapter is:
typing— Support for type hints- Specification for the Python Type System
- Type aliases
- NewType
- Annotating callable objects
- Generics
- Annotating tuples
- The type of class objects
- Annotating generators and coroutines
- User-defined generic types
- The
Anytype - Nominal vs structural subtyping
- Module contents
- Special typing primitives
- Protocols
- ABCs for working with IO
- Functions and decorators
- Introspection helpers
- Constant
- Deprecated aliases
- Deprecation Timeline of Major Features
pydoc— Documentation generator and online help system- Python Development Mode
doctest— Test interactive Python examples- Simple Usage: Checking Examples in Docstrings
- Simple Usage: Checking Examples in a Text File
- How It Works
- Basic API
- Unittest API
- Advanced API
- Debugging
- Soapbox
unittest— Unit testing framework- Basic example
- Command-Line Interface
- Test Discovery
- Organizing test code
- Re-using old test code
- Skipping tests and expected failures
- Distinguishing test iterations using subtests
- Classes and functions
- Test cases
TestCasesetUp()tearDown()setUpClass()tearDownClass()run()skipTest()subTest()debug()assertEqual()assertNotEqual()assertTrue()assertFalse()assertIs()assertIsNot()assertIsNone()assertIsNotNone()assertIn()assertNotIn()assertIsInstance()assertNotIsInstance()assertRaises()assertRaisesRegex()assertWarns()assertWarnsRegex()assertLogs()assertNoLogs()assertAlmostEqual()assertNotAlmostEqual()assertGreater()assertGreaterEqual()assertLess()assertLessEqual()assertRegex()assertNotRegex()assertCountEqual()addTypeEqualityFunc()assertMultiLineEqual()assertSequenceEqual()assertListEqual()assertTupleEqual()assertSetEqual()assertDictEqual()fail()failureExceptionlongMessagemaxDiffcountTestCases()defaultTestResult()id()shortDescription()addCleanup()enterContext()doCleanups()addClassCleanup()enterClassContext()doClassCleanups()
IsolatedAsyncioTestCaseFunctionTestCase
- Grouping tests
- Loading and running tests
TestLoaderTestResulterrorsfailuresskippedexpectedFailuresunexpectedSuccessescollectedDurationsshouldStoptestsRunbufferfailfasttb_localswasSuccessful()stop()startTest()stopTest()startTestRun()stopTestRun()addError()addFailure()addSuccess()addSkip()addExpectedFailure()addUnexpectedSuccess()addSubTest()addDuration()
TextTestResultdefaultTestLoaderTextTestRunnermain()- load_tests Protocol
- Test cases
- Class and Module Fixtures
- Signal Handling
unittest.mock— mock object library- Quick Guide
- The Mock Class
Mockassert_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()calledcall_countreturn_valueside_effectcall_argscall_args_listmethod_callsmock_calls__class__
NonCallableMockPropertyMockAsyncMockThreadingMock- Calling
- Deleting Attributes
- Mock names and the name attribute
- Attaching Mocks as Attributes
- The patchers
- MagicMock and magic method support
- Helpers
- Order of precedence of
side_effect,return_valueand wraps
unittest.mock— getting started- Using Mock
- Mock Patching Methods
- Mock for Method Calls on an Object
- Mocking Classes
- Naming your mocks
- Tracking all Calls
- Setting Return Values and Attributes
- Raising exceptions with mocks
- Side effect functions and iterables
- Mocking asynchronous iterators
- Mocking asynchronous context manager
- Creating a Mock from an Existing Object
- Using side_effect to return per file content
- Patch Decorators
- Further Examples
- Mocking chained calls
- Partial mocking
- Mocking a Generator Method
- Applying the same patch to every test method
- Mocking Unbound Methods
- Checking multiple calls with mock
- Coping with mutable arguments
- Nesting Patches
- Mocking a dictionary with MagicMock
- Mock subclasses and their attributes
- Mocking imports with patch.dict
- Tracking order of calls and less verbose call assertions
- More complex argument matching
- Using Mock
test— Regression tests package for Pythontest.support— Utilities for the Python test suiteTestFailedResourceDeniedverboseis_jythonis_androidunix_shellLOOPBACK_TIMEOUTINTERNET_TIMEOUTSHORT_TIMEOUTLONG_TIMEOUTPGOPIPE_MAX_SIZEPy_DEBUGSOCK_MAX_SIZETEST_SUPPORT_DIRTEST_HOME_DIRTEST_DATA_DIRMAX_Py_ssize_tmax_memusereal_max_memuseMISSING_C_DOCSTRINGSHAVE_DOCSTRINGSTEST_HTTP_URLALWAYS_EQNEVER_EQLARGESTSMALLESTbusy_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()SuppressCrashReportSaveSignalsMatcher
test.support.socket_helper— Utilities for socket teststest.support.script_helper— Utilities for the Python execution teststest.support.bytecode_helper— Support tools for testing correct bytecode generationtest.support.threading_helper— Utilities for threading teststest.support.os_helper— Utilities for os testsFS_NONASCIISAVEDCWDTESTFNTESTFN_NONASCIITESTFN_UNENCODABLETESTFN_UNDECODABLETESTFN_UNICODEEnvironmentVarGuardFakePathset()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— Utilities for import teststest.support.warnings_helper— Utilities for warnings tests