From 21652ded26549aa0655b88bebf62db78c0384176 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20Gr=C3=B6nholm?= Date: Fri, 12 Apr 2024 12:35:34 +0300 Subject: [PATCH] Raise ValueError when get_resource() is called with optional=True and wait_error=True --- src/asphalt/core/_context.py | 7 ++++++- tests/test_context.py | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/asphalt/core/_context.py b/src/asphalt/core/_context.py index 115ac684..b3ed490b 100644 --- a/src/asphalt/core/_context.py +++ b/src/asphalt/core/_context.py @@ -586,14 +586,19 @@ async def get_resource( :param wait: if ``True``, wait for the resource to become available if it's not already available in the context chain :param optional: if ``True``, return ``None`` if the resource was not available + :raises ValueError: if both ``optional=True`` and ``wait=True`` were specified, + as it doesn't make sense :return: the requested resource, or ``None`` if none was available and ``optional`` was ``False`` """ self._ensure_state(ContextState.open, ContextState.closing) - key = (type, name) + + if wait and optional: + raise ValueError("combining wait=True and optional=True doesn't make sense") # First check if there's already a matching resource in this context + key = (type, name) if (resource := self._resources.get(key)) is not None: return cast(T_Resource, resource.value_or_factory) diff --git a/tests/test_context.py b/tests/test_context.py index aa212743..fae04f70 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -351,6 +351,10 @@ async def test_get_resource_not_found(self, context: Context) -> None: assert exc.value.type == int assert exc.value.name == "foo" + async def test_get_resource_optional_wait(self, context: Context) -> None: + with pytest.raises(ValueError, match="doesn't make sense"): + await context.get_resource(int, optional=True, wait=True) + async def test_start_service_task_cancel_on_exit(self) -> None: started = False finished = False