8000 fix: clean up HTTP session and pool during tear down phase (#1007) · nkuik/google-auth-library-python@d057376 · GitHub
[go: up one dir, main page]

Skip to content

Commit d057376

Browse files
fix: clean up HTTP session and pool during tear down phase (googleapis#1007)
* Add unit tests for the change * Fix the unittest to test on the correct class * Make linter happy Co-authored-by: arithmetic1728 <58957152+arithmetic1728@users.noreply.github.com>
1 parent ae2804b commit d057376

File tree

4 files changed

+26
-0
lines changed

4 files changed

+26
-0
lines changed

google/auth/transport/requests.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,10 @@ def __init__(self, session=None):
149149

150150
self.session = session
151151

152+
def __del__(self):
153+
if hasattr(self, "session") and self.session is not None:
154+
self.session.close()
155+
152156
def __call__(
153157
self,
154158
url,

google/auth/transport/urllib3.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,10 @@ def __exit__(self, exc_type, exc_val, exc_tb):
427427
"""Proxy to ``self.http``."""
428428
return self.http.__exit__(exc_type, exc_val, exc_tb)
429429

430+
def __del__(self):
431+
if hasattr(self, "http") and self.http is not None:
432+
self.http.clear()
433+
430434
@property
431435
def headers(self):
432436
"""Proxy to ``self.http``."""

tests/transport/test_requests.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,12 @@ def test_timeout(self):
5151

5252
assert http.request.call_args[1]["timeout"] == 5
5353

54+
def test_session_closed_on_del(self):
55+
http = mock.create_autospec(requests.Session, instance=True)
56+
request = google.auth.transport.requests.Request(http)
57+
request.__del__()
58+
http.close.assert_called_with()
59+
5460

5561
class TestTimeoutGuard(object):
5662
def make_guard(self, *args, **kwargs):

tests/transport/test_urllib3.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,3 +305,15 @@ def test_configure_mtls_channel_without_client_cert_env(
305305
is_mtls = authed_http.configure_mtls_channel(callback)
306306
assert not is_mtls
307307
get_client_cert_and_key.assert_not_called()
308+
309+
def test_clear_pool_on_del(self):
310+
http = mock.create_autospec(urllib3.PoolManager)
311+
authed_http = google.auth.transport.urllib3.AuthorizedHttp(
312+
mock.sentinel.credentials, http=http
313+
)
314+
authed_http.__del__()
315+
http.clear.assert_called_with()
316+
317+
authed_http.http = None
318+
authed_http.__del__()
319+
# Expect it to not crash

0 commit comments

Comments
 (0)
0