Python Fixtures Library

4.3.2 · active · verified Sun Apr 12

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.

Warnings

Install

Imports

Quickstart

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.

import os
from fixtures import Fixture

class TemporaryFileFixture(Fixture):
    def setUp(self):
        super().setUp()
        self.temp_file_path = "temp_data.txt"
        with open(self.temp_file_path, "w") as f:
            f.write("Some temporary test data.")
        print(f"Fixture setup: Created {self.temp_file_path}")

    def cleanUp(self):
        if os.path.exists(self.temp_file_path):
            os.remove(self.temp_file_path)
            print(f"Fixture cleanup: Removed {self.temp_file_path}")
        super().cleanUp()

# Recommended usage as a context manager:
def run_test_with_temp_file():
    with TemporaryFileFixture() as temp_fixture:
        print(f"Test running: Accessing {temp_fixture.temp_file_path}")
        with open(temp_fixture.temp_file_path, "r") as f:
            content = f.read()
            assert content == "Some temporary test data."
        print("Test passed.")

if __name__ == "__main__":
    run_test_with_temp_file()

view raw JSON →