Skip to content

Commit 7101520

Browse files
committed
fix: close all sessions in session_scope even when one close() raises
1 parent 316f815 commit 7101520

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

‎gittensor/utils/github_api_tools.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,8 +202,15 @@ def session_scope() -> Iterator[None]:
202202
finally:
203203
cache = _session_cache
204204
_session_cache = None
205+
first_exc: Optional[Exception] = None
205206
for s in cache.values():
206-
s.close()
207+
try:
208+
s.close()
209+
except Exception as exc:
210+
if first_exc is None:
211+
first_exc = exc
212+
if first_exc is not None:
213+
raise first_exc
207214

208215

209216
def _build_session(token: str) -> requests.Session:

‎tests/utils/test_github_api_tools.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1645,6 +1645,28 @@ def fake_build_session(token):
16451645

16461646
assert github_api_tools._session_cache is None
16471647

1648+
def test_all_sessions_closed_even_when_first_close_raises(self, monkeypatch):
1649+
built: list = []
1650+
1651+
def fake_build_session(token):
1652+
session = Mock()
1653+
session.headers = {}
1654+
built.append(session)
1655+
return session
1656+
1657+
monkeypatch.setattr(github_api_tools, '_build_session', fake_build_session)
1658+
1659+
with pytest.raises(RuntimeError, match='first boom'):
1660+
with _real_session_scope():
1661+
_real_get_session('tokenA')
1662+
_real_get_session('tokenB')
1663+
built[0].close.side_effect = RuntimeError('first boom')
1664+
1665+
assert len(built) == 2
1666+
built[0].close.assert_called_once()
1667+
built[1].close.assert_called_once()
1668+
assert github_api_tools._session_cache is None
1669+
16481670

16491671
if __name__ == '__main__':
16501672
pytest.main([__file__, '-v'])

0 commit comments

Comments
 (0)