python
runtime_error
ai_generated
true
FAILED tests/test_network.py::test_connect - pytest.PytestUnraisableExceptionWarning: Exception ignored in: <socket.socket fd=5> ResourceWarning: unclosed <socket.socket fd=5, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 54321), raddr=('127.0.0.1', 8080)>
ID: python/pytest-warnings-as-errors-unclosed-socket
80%Fix Rate
85%Confidence
0Evidence
2024-07-03First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
Root Cause
pytest is configured with filterwarnings = error, so ResourceWarning from an unclosed socket (e.g., a connection not closed in a fixture or test) is promoted to an error and fails the test.
generic中文
pytest 配置了 filterwarnings = error,因此未关闭的 socket(例如 fixture 或测试中未关闭的连接)产生的 ResourceWarning 被提升为错误并导致测试失败。
Workarounds
-
95% success
import socket import pytest @pytest.fixture def conn(): s = socket.create_connection(('127.0.0.1', 8080)) yield s s.close() def test_connect(conn): ... -
90% success
from contextlib import closing def test_connect(): with closing(socket.create_connection(('127.0.0.1', 8080))) as s: ...
Dead Ends
Common approaches that don't work:
-
70% fail
Hides real resource leaks in production code and can mask other warnings-as-errors that you do want to catch.
-
65% fail
gc.collect() may run before the socket's __del__ or may not close the socket deterministically; the warning can still fire during interpreter shutdown.