Skip to content

Commit

Permalink
Add test for using Container as synchronous context manager
Browse files Browse the repository at this point in the history
  • Loading branch information
ThirVondukr committed Feb 16, 2024
1 parent 4297ab0 commit 69860c0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
5 changes: 4 additions & 1 deletion aioinject/containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ async def __aexit__(
await self._singletons.__aexit__(exc_type, exc_val, exc_tb)

async def aclose(self) -> None:
await self.__aexit__(None, None, None)
await self.__aexit__(None, None, None) # pragma: no cover

def __enter__(self) -> Self:
return self
Expand All @@ -90,3 +90,6 @@ def __exit__(
exc_tb: TracebackType | None,
) -> None:
self._singletons.__exit__(exc_type, exc_val, exc_tb)

def close(self) -> None:
self.__exit__(None, None, None) # pragma: no cover
34 changes: 26 additions & 8 deletions tests/container/test_container.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import contextlib
from collections.abc import AsyncIterator
from collections.abc import AsyncIterator, Iterator
from typing import TYPE_CHECKING

import pytest
Expand Down Expand Up @@ -81,16 +81,34 @@ async def dependency() -> AsyncIterator[int]:
yield 42
shutdown = True

provider = Singleton(dependency)
container = Container()
container.register(Singleton(dependency))
async with container:
for _ in range(2):
async with container.context() as ctx:
assert await ctx.resolve(int) == 42 # noqa: PLR2004

assert shutdown is False
assert shutdown is True


def test_should_close_singletons_sync() -> None:
shutdown = False

@contextlib.contextmanager
def dependency() -> Iterator[int]:
nonlocal shutdown
yield 42
shutdown = True

container = Container()
container.register(provider)
for _ in range(2):
async with container.context() as ctx:
assert await ctx.resolve(int) == 42 # noqa: PLR2004
assert shutdown is False
container.register(Singleton(dependency))
with container:
for _ in range(2):
with container.sync_context() as ctx:
assert ctx.resolve(int) == 42 # noqa: PLR2004

await container.aclose()
assert shutdown is False
assert shutdown is True


Expand Down

0 comments on commit 69860c0

Please sign in to comment.