Python "ResourceWarning: unclosed" failing pytest in CI
ResourceWarning: unclosed file <...> or unclosed <socket> is emitted when an OS resource is finalized without being closed. With filterwarnings = error, pytest turns it into a test failure.
What this error means
A test fails with "ResourceWarning: unclosed file <_io.TextIOWrapper name=...>" or "unclosed <socket.socket ...>" when warnings are treated as errors.
ResourceWarning: unclosed file <_io.TextIOWrapper name='data.txt' mode='r' encoding='UTF-8'>Common causes
A file or socket opened without a context manager
An open() result or a socket was never closed and got finalized later.
A client/session leaked by a fixture
An HTTP session, DB connection, or socket created in setup was not closed in teardown.
How to fix it
Close resources with context managers and fixture teardown
- Use
with open(...) as f:rather than bare open(). - Close clients/sessions in fixture teardown (yield then close).
- Use the traceback to locate the unclosed resource and fix the leak.
@pytest.fixture
def client():
c = httpx.Client()
yield c
c.close()How to prevent it
- Always use context managers for files and sockets.
- Close clients in fixture teardown.
- Run with warnings-as-errors to surface leaks immediately.