Skip to content
Sarj Code Standards

pytest-fixture-returns-closed-resource

Yield a managed fixture resource until its requesting test finishes.

Why

Returning a context-managed stream or HTTPX client exits its context before pytest receives the value. The requesting test receives an already closed resource instead of a usable dependency.

Fix

Yield the resource inside its context so teardown follows the requesting test, updating the generator annotation as needed. If the contract deliberately supplies a closed resource, use an exact SARJ525 suppression with that reason. Review exception and cleanup behavior; no automatic rewrite is provided.

Examples

Before — flagged Returning exits the stream context before the test runs
tests/conftest.py
from io import StringIO
import pytest
@pytest.fixture
def stream():
with StringIO("payload") as handle:
return handle
After — preferred Yield keeps the stream open for the requesting test
tests/conftest.py
from io import StringIO
import pytest
@pytest.fixture
def stream():
with StringIO("payload") as handle:
yield handle