Skip to content

Commit

Permalink
Raise ValueError when get_resource() is called with optional=True and…
Browse files Browse the repository at this point in the history
… wait_error=True
  • Loading branch information
agronholm committed Apr 12, 2024
1 parent 13f88cb commit 21652de
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/asphalt/core/_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 4 additions & 0 deletions tests/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 21652de

Please sign in to comment.