testfixtures
testfixtures is a collection of helpers and mock objects designed to streamline automated testing in Python. It provides utilities for comparing complex objects, mocking methods and classes (including dates, times, and subprocesses), capturing logging and stream output, managing temporary files and directories, and verifying exceptions and warnings. Currently at version 11.0.0, the library is actively maintained with regular updates and improvements.
Warnings
- deprecated The `TempDirectory` class has been deprecated as of version 11. It returned strings for paths. New code should use `TempDir`, which returns `pathlib.Path` objects for improved consistency and utility.
- gotcha When using `testfixtures.compare` or other comparison helpers with objects that implement their own `__eq__` method (e.g., Django model instances), the order of elements within sequences can unexpectedly matter, leading to subtle test failures.
- gotcha Over-reliance on broadly scoped test fixtures, especially those modifying global state or external resources without meticulous cleanup, can lead to slow, confusing, and brittle tests with non-deterministic results. Each test should ideally be isolated and repeatable.
Install
-
pip install testfixtures -
pip install 'testfixtures[yaml,toml,sybil]'
Imports
- TempDir
from testfixtures import TempDir
- compare
from testfixtures import compare
- Replacer
from testfixtures import Replacer
Quickstart
import os
from testfixtures import TempDir
# Create a temporary directory
with TempDir() as d:
# Write a file to the temporary directory
d.write('my_file.txt', b'Hello, testfixtures!')
d.makedir('my_subdir')
# Verify contents and structure
print(f"Files in temporary directory: {sorted(os.listdir(d.path))}")
assert 'my_file.txt' in os.listdir(d.path)
assert 'my_subdir' in os.listdir(d.path)
with open(os.path.join(d.path, 'my_file.txt'), 'rb') as f:
content = f.read()
print(f"Content of my_file.txt: {content.decode()}")
assert content == b'Hello, testfixtures!'
# The temporary directory and its contents are automatically cleaned up here