Skip to content

Commit

Permalink
Add a helpful exception when forgetting to await an async class (#396)
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobtomlinson authored Jun 4, 2024
1 parent b1440eb commit b1b5210
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
23 changes: 18 additions & 5 deletions kr8s/_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,14 @@ def __init__(self, resource: dict, namespace: str = None, api: Api = None) -> No
)
if namespace is not None:
self._raw["metadata"]["namespace"] = namespace
self.api = api
if self.api is None and not self._asyncio:
self.api = kr8s.api()
self._api = api
if self._api is None and not self._asyncio:
self._api = kr8s.api()

def __await__(self):
async def f():
if self.api is None:
self.api = await kr8s.asyncio.api()
if self._api is None:
self._api = await kr8s.asyncio.api()
return self

return f().__await__()
Expand All @@ -108,6 +108,19 @@ def __eq__(self, other):
return False
return True

@property
def api(self):
if self._api is None and self._asyncio:
raise RuntimeError(
f"{self.__repr__()} has not been initialized with an API object. "
"Did you forget to await it?"
)
return self._api

@api.setter
def api(self, value):
self._api = value

@property
def raw(self) -> str:
"""Raw object returned from the Kubernetes API."""
Expand Down
7 changes: 7 additions & 0 deletions kr8s/tests/test_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,13 @@ async def test_pod_wait_ready(example_pod_spec):
await pod.wait("delete")


async def test_pod_missing_await_error(example_pod_spec):
pod = Pod(example_pod_spec) # We intentionally forget to await here
assert pod._api is None
with pytest.raises(RuntimeError, match="forget to await it"):
await pod.create()


async def test_pod_wait_multiple_conditions(example_pod_spec):
pod = await Pod(example_pod_spec)
await pod.create()
Expand Down

0 comments on commit b1b5210

Please sign in to comment.