Skip to content

Commit

Permalink
Raise TypeError on get(async_factory)
Browse files Browse the repository at this point in the history
Fixes #21
  • Loading branch information
hynek committed Aug 8, 2023
1 parent 0104165 commit 5f6a016
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ You can find our backwards-compatibility policy [here](https://github.com/hynek/
- Factory results of None are now treated like every other result and cached.
[#22](https://github.com/hynek/svcs/pull/22)

- Calling `Container.get()` on a service that has an async factory now raises a `TypeError`.
[#21](https://github.com/hynek/svcs/pull/21)


### Added

Expand Down
4 changes: 4 additions & 0 deletions src/svcs/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,10 @@ def get(self, *svc_types: type) -> object:
continue

rs = self.registry.get_registered_service_for(svc_type)
if rs.is_async:
msg = "Please use `aget()` for async factories."
raise TypeError(msg)

svc = rs.factory(self) if rs.takes_container else rs.factory()

if isinstance(svc, Generator):
Expand Down
19 changes: 18 additions & 1 deletion tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
# SPDX-License-Identifier: MIT

import asyncio
import re

import pytest

import svcs

from .fake_factories import nop
from .fake_factories import async_int_factory, async_str_cleanup_factory, nop
from .ifaces import AnotherService, Interface, Service, YetAnotherService


Expand Down Expand Up @@ -200,6 +201,22 @@ def factory():
assert 1 == i


@pytest.mark.parametrize(
"factory", [async_int_factory, async_str_cleanup_factory]
)
def test_get_on_async_factory_raises_type_error(registry, container, factory):
"""
get() on an async factory raises a TypeError.
"""

registry.register_factory(Service, factory)

with pytest.raises(
TypeError, match=re.escape("Please use `aget()` for async factories.")
):
container.get(Service)


@pytest.mark.asyncio()
class TestAsync:
async def test_async_factory(self, registry, container):
Expand Down

0 comments on commit 5f6a016

Please sign in to comment.