testfixtures

11.0.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates the `TempDir` context manager, a fundamental tool for safely creating and managing temporary files and directories within tests. The directory and its contents are automatically removed upon exiting the `with` block.

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

view raw JSON →