Skip to content

[BUG] pytest hangs when using async_get_injected_obj #186

Description

@Nemesis7

Describe the bug
So I cannot pinpoint it just yet, but when using async_get_injected_obj to load a class e.g. self.handler = await async_get_injected_obj(HandlerClass), it will hang when running pytest via command line poetry run pytest tests\handlers.py

Now I've switched back to an old implementation to load these classes (can't remember where I found this) and it just works:

async def solve_command(request: Request, dependant: Dependant) -> Any:
    """
    Helper function to solve dependencies.
    """
    async with AsyncExitStack() as cm:
        solved_dependency = await solve_dependencies(
            request=request, dependant=dependant, embed_body_fields=False, async_exit_stack=cm
        )
        values = solved_dependency.values
        errors = solved_dependency.errors
        if errors:
            raise ValidationError(errors, None)
        if inspect.iscoroutinefunction(dependant.call):
            result = await dependant.call(**values)
        else:
            result = dependant.call(**values)  # type: ignore

        return result


async def load_with_dependencies(command: Callable) -> Any:
    """
    Wrapper which creates a fake Request to resolve all dependencies within a class,
    using the dependency injection offered by FastAPI.
    """
    async with AsyncExitStack() as cm:
        request = Request({"type": "http", "headers": [], "query_string": "", "fastapi_astack": cm})

        dependant = get_dependant(path="command", call=command, use_cache=False)

        return await solve_command(request, dependant)

pytest just hangs, and nothing happens, no error, no timeout. Also because I'm using httpx, I needed to add this in the pyproject.toml file:

# needed when using httpx, see https://github.com/pytest-dev/pytest-asyncio/issues/868
asyncio_default_fixture_loop_scope = "session"
asyncio_default_test_loop_scope = "session"

Note that the tests just work in sequence when ran from the IDE (IntelliJ IDEA), but not when run via pytest.

To Reproduce
So I don't know how to reproduce, except that it breaks if there are multiple tests with multiple api calls

Expected behavior
I'd expect the pytest tests to run as expected

Screenshots

OS
macosx Tahoe 26.1

Version

  1. Python: 3.13
  2. FastAPI: 0.120.4

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions