Wraps callables to capture stdout, stderr, exceptions and the return
Project description
Method Capture
Wraps callables to capture stdout, stderr, exceptions and the return.
Why?
This library was created to assist in the testing of Python code, where return values and exceptions are important, in addition to what is written to stdout and stderr. It allows for a callable to be ran without the caller being concerned with how important outputs are captured.
An example use is when writing common code to test both a Python interface and a corresponding CLI (tested by invoking main). A common test procedure - which may involve a complex setup and tear down - can be ran using the different interfaces and return results that encapsulate the outputs, without concern over the form they take (e.g. the Python interface may have returned True on success but the CLI may have called exit(0), with raises a SystemExit exception).
Other alternatives exist for capturing stdout and stderr but none also handle exceptions.
How?
from capturewrap import CaptureWrapBuilder
builder = CaptureWrapBuilder(capture_stdout=True, capture_stderr=True, capture_exception=True)
wrapped = builder.build(my_method)
result = wrapped(*args, **kwargs)
print(f"stdout: {result.stdout}")
print(f"stderr: {result.stderr}")
print(f"return_value: {result.return_value}")
print(f"exception: {result.exception}")
Note: if an exception is captured, return_value will be None.
Requirements
Python >= 3.6
Installation
Stable releases can be installed via PyPI:
$ pip install capturewrap
Bleeding edge versions can be installed directly from GitHub:
$ pip install git+https://github.com/wtsi-hgi/python-capturewrap.git@$commitOrBranch#egg=capturewrap
Implementation
This implementation captures stdout and stdin using `redirect_stdout <https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout>`__ and `redirect_stderr <https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stderr>`__, which were added to the standard library in Python 3.5.
Alternatives
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file capturewrap-1.0.1.tar.gz
.
File metadata
- Download URL: capturewrap-1.0.1.tar.gz
- Upload date:
- Size: 5.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | edd7434f21c71b5449e636dc33ed7356b3e8ad7cdaf90ec2ed3b18c4b09c5963 |
|
MD5 | 80280f9b91317efea8bb311bb0f9fd69 |
|
BLAKE2b-256 | f75aa7cf841ebc7c7d13d59e8db8064174e81a3cc61695314e54247fe2140695 |