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
Any
type - 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
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()
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
FunctionTestCase
- Grouping tests
- Loading and running tests
TestLoader
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
main()
- load_tests Protocol
- Test cases
- Class and Module Fixtures
- Signal Handling
unittest.mock
— mock object library- Quick Guide
- The Mock Class
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
ThreadingMock
- 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_value
and 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 suiteTestFailed
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
Matcher
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_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
— Utilities for import teststest.support.warnings_helper
— Utilities for warnings tests