From b1b52100a91acd6a0bfbb911d21829f177a86bcd Mon Sep 17 00:00:00 2001 From: Jacob Tomlinson Date: Tue, 4 Jun 2024 13:22:22 +0100 Subject: [PATCH] Add a helpful exception when forgetting to await an async class (#396) --- kr8s/_objects.py | 23 ++++++++++++++++++----- kr8s/tests/test_objects.py | 7 +++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/kr8s/_objects.py b/kr8s/_objects.py index c7147640..facd70d8 100644 --- a/kr8s/_objects.py +++ b/kr8s/_objects.py @@ -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__() @@ -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.""" diff --git a/kr8s/tests/test_objects.py b/kr8s/tests/test_objects.py index 283105ef..01e2a6f7 100644 --- a/kr8s/tests/test_objects.py +++ b/kr8s/tests/test_objects.py @@ -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()