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.
pytest
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.
Python
@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.
Related guides
Python "pytest.PytestUnraisableExceptionWarning" in CIFix "pytest.PytestUnraisableExceptionWarning" in CI - an exception was raised in a __del__ or weakref callbac…
Python "OSError: [Errno 24] Too many open files" in CIFix Python "OSError: [Errno 24] Too many open files" (EMFILE) in CI - a file-descriptor leak or a too-low uli…
pytest "ResourceWarning: unclosed" Failing CI - Fix Leaked HandlesFix pytest "ResourceWarning: unclosed file/socket" failing CI under warnings-as-errors - close handles with c…