Skip to content

Commit

Permalink
add support for contextlib
Browse files Browse the repository at this point in the history
  • Loading branch information
jschlyter committed Nov 20, 2024
1 parent f360b64 commit bbe34ca
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
15 changes: 14 additions & 1 deletion dnstapir/key_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,19 @@ def httpx_client(self) -> httpx.Client:
self._httpx_client = httpx.Client()
return self._httpx_client

def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.close()

def __del__(self):
self.close()

def close(self):
"""Explicitly close the client and free resources."""
if self._httpx_client is not None:
self._httpx_client.close()
try:
self._httpx_client.close()
finally:
self._httpx_client = None
15 changes: 14 additions & 1 deletion tests/test_key_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,19 @@ def test_url_key_resolver(httpx_mock: HTTPXMock):
httpx_mock.add_response(url=f"https://keys/{key_id}.pem", content=public_key_pem)

resolver = UrlKeyResolver(client_database_base_url="https://keys")

res = resolver.resolve_public_key(key_id)
assert res == public_key


def test_url_key_resolver_contextlib(httpx_mock: HTTPXMock):
key_id = "xyzzy"
public_key = ed25519.Ed25519PrivateKey.generate().public_key()
public_key_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo
)

httpx_mock.add_response(url=f"https://keys/{key_id}.pem", content=public_key_pem)

with UrlKeyResolver(client_database_base_url="https://keys") as resolver:
res = resolver.resolve_public_key(key_id)
assert res == public_key

0 comments on commit bbe34ca

Please sign in to comment.