hbutils.testing.capture.exit
Exit code capture utilities for test environments.
This module provides context managers and result models for capturing exit codes
raised by sys.exit() or quit() without terminating the running
process. It is primarily intended for unit testing scenarios where code paths
that call system exit functions need to be verified safely.
The module contains the following main components:
ExitCaptureResult- Stores the captured exit codecapture_exit()- Context manager that intercepts exit calls
Note
The implementation patches sys.exit(). The built-in quit()
delegates to sys.exit(), so it is captured by the same mechanism.
Example:
>>> from hbutils.testing.capture.exit import capture_exit
>>> with capture_exit() as result:
... pass
>>> result.exitcode
0
>>> with capture_exit() as result:
... quit(3)
>>> result.exitcode
3
__all__
- hbutils.testing.capture.exit.__all__ = ['capture_exit', 'ExitCaptureResult']
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.
ExitCaptureResult
- class hbutils.testing.capture.exit.ExitCaptureResult(exitcode: int)[source]
Model of exit capture result.
This class stores the captured exit code from a context where exit calls are intercepted by
capture_exit().- Parameters:
exitcode (int) – Initial exit code to store.
- __init__(exitcode: int) None[source]
Initialize the result container.
- Parameters:
exitcode (int) – Initial exit code to store.
- property exitcode: int
Get the captured exit code.
- Returns:
The exit code captured by
capture_exit().- Return type:
int
Note
Do not access this property before
capture_exit()finishes, otherwise the result may not be finalized.
capture_exit
- hbutils.testing.capture.exit.capture_exit(default: int = 0) ContextManager[ExitCaptureResult][source]
Capture system exit calls and store the resulting exit code.
This context manager intercepts calls to
sys.exit()(and thereforequit()) and stores the exit code in anExitCaptureResultinstance instead of terminating the process.- Parameters:
default (int) – Default exit code when no exit is invoked, defaults to
0.- Returns:
Context manager yielding an
ExitCaptureResultinstance.- Return type:
ContextManager[ExitCaptureResult]
Example:
>>> from hbutils.testing.capture.exit import capture_exit >>> with capture_exit() as ex: ... pass >>> ex.exitcode 0 >>> >>> with capture_exit() as ex: ... quit() >>> ex.exitcode 0 >>> >>> with capture_exit() as ex: ... quit(0xf) >>> ex.exitcode 15 >>> >>> import sys >>> with capture_exit() as ex: ... sys.exit(0xf) >>> ex.exitcode 15