pytest "ResourceWarning: unclosed" Failing CI - Fix Leaked Handles
A ResourceWarning: unclosed means a file, socket, or similar handle was garbage-collected without being closed. Under warnings-as-errors it fails the test; it also signals a real resource leak worth fixing.
What this error means
A test fails (or warns loudly) with ResourceWarning: unclosed file <_io.TextIOWrapper ...> or unclosed <socket.socket ...>. With filterwarnings = error it is a hard failure; otherwise it is intermittent and order-dependent.
E ResourceWarning: unclosed file <_io.TextIOWrapper name='data.txt' mode='r'
encoding='UTF-8'>
tests/test_io.py::test_readCommon causes
A handle opened without being closed
Code (or a test/fixture) opens a file or socket and never closes it; the warning fires when the object is finalized.
A fixture leaking a connection
A fixture that yields a client/connection without proper teardown leaks the resource, surfacing as an unclosed warning later.
How to fix it
Use context managers
Wrap resources in with so they close deterministically.
with open("data.txt", encoding="utf-8") as f:
data = f.read()
# files, sockets, and DB connections all support context managersClose resources in fixture teardown
Ensure yield fixtures clean up the resource they create.
@pytest.fixture
def client():
c = make_client()
try:
yield c
finally:
c.close()How to prevent it
- Always manage files/sockets/connections with context managers.
- Give yield fixtures explicit teardown that closes resources.
- Keep
filterwarnings = errorso leaks fail fast instead of flaking.