pytest-reraise

2.1.2 · active · verified Fri Apr 17

pytest-reraise is a pytest plugin designed to make multi-threaded test cases fail when exceptions occur in background threads. Without it, exceptions in threads separate from the main test thread might not be caught by pytest, leading to silently passing tests. The current version is 2.1.2, with a release cadence that focuses on bug fixes and minor feature enhancements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `pytest-reraise` to catch exceptions that occur in background threads. Without `Reraise.wrap()`, `pytest` would typically miss these exceptions, allowing the test to pass even if a critical error occurred in a non-main thread.

import threading
from pytest_reraise import Reraise
import pytest

def test_threaded_exception_is_caught():
    # This test will fail due to the ValueError in the thread
    # because pytest-reraise ensures the exception is re-raised.
    
    # Option 1: Instantiate Reraise
    reraise_instance = Reraise()
    def func_with_error():
        raise ValueError("This exception should fail the test!")

    thread_with_error = threading.Thread(target=reraise_instance.wrap(func_with_error))
    thread_with_error.start()
    thread_with_error.join()

    # Option 2: Use the class method (introduced in v2.1.0)
    def another_func_with_error():
        # Example of a division by zero
        _ = 1 / 0
    
    thread_with_another_error = threading.Thread(target=Reraise.wrap(another_func_with_error))
    thread_with_another_error.start()
    thread_with_another_error.join()

# To run this example:
# 1. Save it as `test_example.py`
# 2. Run `pytest test_example.py` in your terminal.
# Expected outcome: Both parts of the test will raise exceptions and cause the test to fail.

view raw JSON →