How can I test my use cases setting up correctly my dependency injection containers?

Viewed 31

Im using dependency_injection python lib and having issues to test my use_cases.

I have this conatiners:

class TestAdapters(containers.DeclarativeContainer):
    repository: RepositoryInterface = providers.Singleton(
        MockRepository
    ).add_args(1)
    ... # More adapters here


class Adapters(containers.DeclarativeContainer):
    repository: RepositoryInterface = providers.Singleton(
        RedisRepository
    ).add_args(1)
    ...

class UseCases(containers.DeclarativeContainer):
    adapters = providers.DependenciesContainer()

    example_use_case: ExampleUseCaseInterface = providers.Factory(
        ExampleUseCase, repository=adapters.respository
    )
    ...

def get_adapter():
    import os

    if os.getenv("ENVIRONMENT") == "TEST":
        return TestAdapters()
    return Adapters()

In my API, setting the dependecies like this:

# Fast api main.py file
def get_application() -> FastAPI:
    container = UseCases(adapters=get_adapter())
    container.wire(modules=["adapters.api.v1.controllers"])

    application = FastAPI(
        title=settings.PROJECT_NAME,
    )
    application.include_router(router)
    application.middleware("http")(catch_exceptions_middleware)

    return application

But I'm trying to test my use cases in isolation, without necessarily going through the api. So my strategy is to create a use_cases fixture, which returns UseCases container with the right Adapters container setted:

# In global conftest.py
@pytest.fixture
def use_cases():
    container = UseCases(adapters=TestAdapters())
    container.wire(modules=["adapters.api.v1.controllers"])
    yield container
    container.unwire()

But when I run any test with use_cases as fixture I have this error:

dependency_injector.errors.Error: Dependency "UseCases.adapters.respository" is not defined

What am I missing here? There is a better way to do it?

1 Answers

There is nothing wrong with my implementation. My problem was that there was a typo on my use_case Factory on UseCases container.

Related