pytest-threadleak

0.5.0 · active · verified Fri Apr 17

pytest-threadleak is a pytest plugin that automatically detects non-daemon thread leaks after tests complete. It helps identify when tests leave background threads running, which can cause resource exhaustion or unexpected behavior. The current version is 0.5.0, and it is maintained with releases as needed for bug fixes or new features.

Common errors

Warnings

Install

Imports

Quickstart

To get started, simply install `pytest-threadleak` and include the `threadleak` fixture in your test functions. The plugin automatically checks for new non-daemon threads spawned during the test that are still active when the test finishes. The example demonstrates a clean test and how to intentionally create a leak to see the plugin in action.

import threading
import time

# test_my_app.py

def test_my_function_no_leak(threadleak):
    """
    This test uses the 'threadleak' fixture to ensure no new
    non-daemon threads are left running after the test completes.
    This specific test should pass cleanly.
    """
    def do_something_brief():
        time.sleep(0.01)
    
    t = threading.Thread(target=do_something_brief)
    t.start()
    t.join() # Ensure the thread finishes before the test does

# To run this test:
# pip install pytest-threadleak pytest
# pytest test_my_app.py

# To observe a leak (uncomment and run):
# def test_my_function_with_leak(threadleak):
#     """
#     This test will intentionally leave a non-daemon thread running,
#     causing pytest-threadleak to report a ThreadLeakError.
#     """
#     def infinite_loop():
#         while True:
#             time.sleep(0.1)
#     
#     threading.Thread(target=infinite_loop).start()

view raw JSON →