'How to use Flask's test_client with dependency injection?

I have a basic Flask app with GET endpoints. I want to spin it up so writing functional/end-to-end tests for it but with Dependency Injection, I'm finding it hard to start it up. This is what my app looks like:

__init__.py:

def create_app():
    container = Container()
    container.init_resources()
    app = Flask(__name__)
    app.container = container
    
    # connect url rules and register error handlers
    routes.configure(app)

    return app

containers.py:

class Container(containers.DeclarativeContainer):

    wiring_config = containers.WiringConfiguration(modules=[".routes"])

    config = providers.Configuration(yaml_files=["src/conf/config.yaml"])
    config.load(envs_required=True)
    s3_repository = providers.Resource(
        S3Repository, config.get("app.my_service.s3_bucket")
    )

    my_service = providers.Singleton(
        MyService, config, s3_repository
    )

I'm trying to test it like:

from unittest.mock import Mock, patch

from dependency_injector.providers import Configuration
from dependency_injector.containers import Container

from src import create_app


@patch('dependency_injector.providers.Configuration')
def test_something(mk_config):
    mk_config = Configuration()
    mk_config.from_dict(options=dict(app="hey world!"))
    app = create_app()
    app.test_client().get("/")
    

But of course it fails! It fails with a strange error:

../src/__init__.py:11: in create_app
    container = Container()
src/dependency_injector/containers.pyx:742: in dependency_injector.containers.DeclarativeContainer.__new__
    ???
src/dependency_injector/containers.pyx:392: in dependency_injector.containers.DynamicContainer.load_config
    ???
src/dependency_injector/containers.pyx:193: in traverse
    ???
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

>   ???
E   TypeError: isinstance() arg 2 must be a type or tuple of types

src/dependency_injector/providers.pyx:4818: TypeError

I don't know how to get past this error! What am I doing wrong? I don't think I should even be applying that patch (I was just tinkering with it so I could see if values are being loaded in the test_client). What is the right way to start up a test app with config values?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source