Skip to content
Latchkey

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

  1. Use with open(...) as f: rather than bare open().
  2. Close clients/sessions in fixture teardown (yield then close).
  3. 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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →