The `fixtures` library (not to be confused with `pytest` fixtures) provides a Python contract for reusable state and support logic, primarily for unit testing. It includes helper and adaptation logic to simplify writing fixtures and offers glue code for `unittest`-compatible test cases. As of version 4.3.2, released in March 2026, the library is actively maintained and supports Python 3.10 and newer. It offers a set of pre-canned fixtures like `LogHandler`, `MockPatchObject`, and `MonkeyPatch` for common testing scenarios.
pip install fixturesVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to create a custom `Fixture` that manages a temporary file. The `with` statement handles the `setUp` and `cleanUp` methods automatically, ensuring resources are properly managed before and after the test operation.
Use the fixture as a context manager (`with MyFixture(): ...`) or ensure `setUp()` and `cleanUp()` are explicitly called in your test's setup and teardown methods (e.g., `unittest.TestCase.setUp` and `tearDown`).
Consult the specific documentation for `fixtures.MonkeyPatch` for best practices when patching methods. Consider alternative mocking strategies if encountering issues.
Ensure that your `setUp()` and `cleanUp()` methods thoroughly isolate or reset any mutable state your fixture introduces or modifies. Prefer creating fresh fixture instances or using context managers where possible for critical isolation.
Install the library using pip: `pip install fixtures`
Install the library using pip: `pip install testfixtures` (or `pip install fixtures` and update the import statement to `import fixtures` if preferred)
Ensure that `LogCapture` or `log_capture` is initialized with either positional arguments or keyword arguments, but not both for the same parameter. For example, use `LogCapture(level=logging.ERROR, names='my_logger')` or `LogCapture('my_logger', level=logging.ERROR)` but not `LogCapture('my_logger', names='my_logger')`.Change the import statement from `from fixtures import MonkeyPatch` to `from fixtures.monkeypatch import MonkeyPatch` or `import fixtures.monkeypatch` and then use `fixtures.monkeypatch.MonkeyPatch`.
Configure the test runner's logging capture (e.g., `pytest -p no:logging` or `log_file_level` in `pytest.ini`) or ensure that custom log handlers manage their streams carefully within the test's lifecycle, potentially using a context manager or ensuring handlers are removed before stream closure.