Ejemplo n.º 1
0
class Repositories(containers.DeclarativeContainer):
    config = providers.Configuration()

    db = providers.Factory(
        Database,
        conn_str=config.connection_string
    )
Ejemplo n.º 2
0
class Container(containers.DeclarativeContainer):

    config = providers.Configuration()

    movie = providers.Factory(entities.Movie)

    csv_finder = providers.Singleton(
        finders.CsvMovieFinder,
        movie_factory=movie.provider,
        path=config.finder.csv.path,
        delimiter=config.finder.csv.delimiter,
    )

    sqlite_finder = providers.Singleton(
        finders.SqliteMovieFinder,
        movie_factory=movie.provider,
        path=config.finder.sqlite.path,
    )

    finder = providers.Selector(
        config.finder.type,
        csv=csv_finder,
        sqlite=sqlite_finder,
    )

    lister = providers.Factory(
        listers.MovieLister,
        movie_finder=finder,
    )
        class NestedContainer(containers.DeclarativeContainer):
            settings = providers.Configuration()

            print_settings = providers.Callable(
                lambda s: s,
                settings,
            )
Ejemplo n.º 4
0
    def test_providers_with_default_value_overriding(self):
        self.config = providers.Configuration(
            name='config', default={'a': {
                'b': {
                    'c': 1,
                    'd': 2
                }
            }})

        self.assertEqual(self.config.a(), {'b': {'c': 1, 'd': 2}})
        self.assertEqual(self.config.a.b(), {'c': 1, 'd': 2})
        self.assertEqual(self.config.a.b.c(), 1)
        self.assertEqual(self.config.a.b.d(), 2)

        self.config.override({'a': {'b': {'c': 3, 'd': 4}}})
        self.assertEqual(self.config.a(), {'b': {'c': 3, 'd': 4}})
        self.assertEqual(self.config.a.b(), {'c': 3, 'd': 4})
        self.assertEqual(self.config.a.b.c(), 3)
        self.assertEqual(self.config.a.b.d(), 4)

        self.config.reset_override()
        self.assertEqual(self.config.a(), {'b': {'c': 1, 'd': 2}})
        self.assertEqual(self.config.a.b(), {'c': 1, 'd': 2})
        self.assertEqual(self.config.a.b.c(), 1)
        self.assertEqual(self.config.a.b.d(), 2)
Ejemplo n.º 5
0
class IocContainer(containers.DeclarativeContainer):
    """
        Define dependencies and inject them into data and service layers when creating Flask app.
    """

    config = providers.Configuration('config', default={
        'SQLALCHEMY_DATABASE_URI': 'mysql+pymysql://root:@localhost/community',
        'LOG_PATH': 'rest-api-prototype.log',
        'SQLALCHEMY_ECHO': True,
        'CACHE_TYPE': 'simple',
        'CACHE_DEFAULT_TIMEOUT': 300
    })

    app = providers.Factory(Flask, __name__)

    cache = providers.Dependency(instance_of=Cache)

    logger = providers.Dependency(instance_of=Logger)

    db = providers.Dependency(instance_of=SQLAlchemy)

    db_session = providers.Dependency(instance_of=ScopedSession)

    community_dao = providers.Dependency(instance_of=CommunityDao)

    community_service = providers.Singleton(CommunityService, community_dao, logger)
Ejemplo n.º 6
0
class Core(containers.DeclarativeContainer):

    config = providers.Configuration('config')

    logger = providers.Singleton(logging.Logger, name='log')

    presence_logger = providers.Singleton(logging.Logger, name='presence_logger')
Ejemplo n.º 7
0
class Container(containers.DeclarativeContainer):

    app = flask.Application(Flask, __name__)

    # Configuración
    config = providers.Configuration('config')

    # Dependencias
    logger = providers.Singleton(logging.Logger, name='logger')
    psycopg2_data_manager = providers.Singleton(Psycopg2DataManager,
                                                user=config.username,
                                                password=config.password,
                                                host=config.host,
                                                port=config.port,
                                                db_name=config.db_name)

    sqlalchemy_orm_data_manager = providers.Singleton(SqlAlchemyORMDataManager,
                                                      user=config.username,
                                                      password=config.password,
                                                      host=config.host,
                                                      port=config.port,
                                                      db_name=config.db_name)

    # Servicios
    gestor_pedidos = providers.Selector(
        config.data_handler,
        psycopg2=providers.Singleton(GestorPedidos, psycopg2_data_manager,
                                     logger),
        sqlalchemy=providers.Singleton(GestorPedidos,
                                       sqlalchemy_orm_data_manager, logger),
    )
Ejemplo n.º 8
0
class Container(containers.DeclarativeContainer):
    config = providers.Configuration()
    active_url = None
    active_token = None

    log = providers.Resource(
        logging.config.fileConfig,
        fname="logging.ini",
    )

    if config.application.environment:
        active_url = config.uat.url
        active_token = config.uat.token
    else:
        # Set as per Environment
        url = None
        token = None

    client_session = providers.Singleton(Session)

    b2c2_client = providers.Factory(
        B2C2Client,
        session=client_session,
        url=active_url,
        token=active_token,
    )
Ejemplo n.º 9
0
class Container(containers.DeclarativeContainer):

    config = providers.Configuration()

    notify_service = providers.Singleton(NotifyService,
                                         api_key=config.NOTIFY_API_KEY,
                                         end_point=config.NOTIFY_ENDPOINT)
    def setUp(self):
        self.config = providers.Configuration(name='config')

        class Section11(pydantic.BaseModel):
            value1 = 1

        class Section12(pydantic.BaseModel):
            value2 = 2

        class Settings1(pydantic.BaseSettings):
            section1 = Section11()
            section2 = Section12()

        self.Settings1 = Settings1

        class Section21(pydantic.BaseModel):
            value1 = 11
            value11 = 11

        class Section3(pydantic.BaseModel):
            value3 = 3

        class Settings2(pydantic.BaseSettings):
            section1 = Section21()
            section3 = Section3()

        self.Settings2 = Settings2
class Container(containers.DeclarativeContainer):

    config = providers.Configuration()

    database = providers.Singleton(
        databases.Database,
        url=config.db.connection_string
    )

    var_service = providers.Factory(
        VariableService,
        database=database
    )

    env_service = providers.Factory(
        EnvironmentService,
        database=database,
        var_service=var_service
    )

    app_service = providers.Factory(
        ApplicationService,
        database=database,
        env_service=env_service
    )

    change_history_service = providers.Factory(
        ChangeHistoryService,
        database=database,
        app_service=app_service,
        env_service=env_service,
        var_service=var_service
    )
Ejemplo n.º 12
0
def test_double_override():
    root_config = providers.Configuration("main")
    core = Core(config=root_config.core)
    services = Services(config=root_config.services)

    root_config.override(
        {
            "core": {
                "value": "core1",
            },
            "services": {
                "value": "services1",
            },
        }, )
    root_config.override(
        {
            "core": {
                "value": "core2",
            },
            "services": {
                "value": "services2",
            },
        }, )

    assert core.config() == {"value": "core2"}
    assert core.config.value() == "core2"
    assert core.value_getter() == "core2"

    assert services.config() == {"value": "services2"}
    assert services.config.value() == "services2"
    assert services.value_getter() == "services2"
Ejemplo n.º 13
0
class ApplicationContainer(containers.DeclarativeContainer):

    config = providers.Configuration()

    sqlite = providers.Singleton(sqlite3.connect, config.database.dsn)

    s3 = providers.Singleton(
        boto3.client,
        service_name='s3',
        aws_access_key_id=config.aws.access_key_id,
        aws_secret_access_key=config.aws.secret_access_key,
    )

    user_package = providers.Container(
        UserContainer,
        database=sqlite,
    )

    photo_package = providers.Container(
        PhotoContainer,
        database=sqlite,
        file_storage=s3,
    )

    analytics_package = providers.Container(
        AnalyticsContainer,
        user_repository=user_package.user_repository,
        photo_repository=photo_package.photo_repository,
    )
Ejemplo n.º 14
0
class Container(containers.DeclarativeContainer):
    config = providers.Configuration()
    config.from_ini('./GiysApi/config.ini')
    rmq = config.RMQ

    logger = providers.Factory(Logger)

    rmq_connection = providers.Factory(Connection,
                                       hostname=rmq.hostname,
                                       username=rmq.username,
                                       password=rmq.password)

    task_logger = providers.Factory(TaskLogger)

    register_manager = providers.Factory(RegisterManager)

    message_handler = providers.Factory(MessageHandler,
                                        task_logger=task_logger,
                                        register_manager=register_manager)

    message_consumer = providers.Factory(MessageConsumer,
                                         connection=rmq_connection,
                                         message_handler=message_handler,
                                         logger=logger)

    message_service = providers.Factory(MessageService,
                                        connection=rmq_connection)

    task_manager = providers.Factory(TaskManager,
                                     message_service=message_service,
                                     task_logger=task_logger)
Ejemplo n.º 15
0
class Container(containers.DeclarativeContainer):

    config = providers.Configuration()

    session = providers.Resource(
        boto3.session.Session,
        aws_access_key_id=config.aws_access_key_id,
        aws_secret_access_key=config.aws_secret_access_key,
        aws_session_token=config.aws_session_token,
    )

    s3_client = providers.Resource(
        session.provided.client.call(),
        service_name="s3",
    )

    sqs_client = providers.Resource(
        providers.MethodCaller(session.provided.client),  # Alternative syntax
        service_name="sqs",
    )

    service1 = providers.Factory(
        Service,
        s3_client=s3_client,
        sqs_client=sqs_client,
    )

    service2 = providers.Factory(
        Service,
        s3_client=session.provided.client.call(
            service_name="s3"),  # Alternative inline syntax
        sqs_client=session.provided.client.call(
            service_name="sqs"),  # Alternative inline syntax
    )
    def test_double_override(self):
        root_config = providers.Configuration('main')
        core = self.TestCore(config=root_config.core)
        services = self.TestServices(config=root_config.services)

        root_config.override(
            {
                'core': {
                    'value': 'core1',
                },
                'services': {
                    'value': 'services1',
                },
            },
        )
        root_config.override(
            {
                'core': {
                    'value': 'core2',
                },
                'services': {
                    'value': 'services2',
                },
            },
        )

        self.assertEqual(core.config(), {'value': 'core2'})
        self.assertEqual(core.config.value(), 'core2')
        self.assertEqual(core.value_getter(), 'core2')

        self.assertEqual(services.config(), {'value': 'services2'})
        self.assertEqual(services.config.value(), 'services2')
        self.assertEqual(services.value_getter(), 'services2')
Ejemplo n.º 17
0
class HeaterControlContainer(containers.DeclarativeContainer):
    config = providers.Configuration()
    first_heater_controller = providers.Factory(RelayController, 2)
    second_heater_controller = providers.Factory(RelayController, 4)
    heater_status_repository = providers.Singleton(HeaterStatusRepository,
                                                   first_heater_controller,
                                                   second_heater_controller)
Ejemplo n.º 18
0
class Core(containers.DeclarativeContainer):
    """ the container for core components of the program """
    config = providers.Configuration('config')

    logger = providers.Singleton(Logger,
                                 name=config.logging.name,
                                 view_level=config.logging.level)
Ejemplo n.º 19
0
class ApplicationContainer(containers.DeclarativeContainer):
    """Application container."""

    app = flask.Application(Flask, __name__)

    bootstrap = flask.Extension(Bootstrap)

    config = providers.Configuration()

    github_client = providers.Factory(
        Github,
        login_or_token=config.github.auth_token,
        timeout=config.github.request_timeout,
    )

    search_service = providers.Factory(
        services.SearchService,
        github_client=github_client,
    )

    index_view = flask.View(
        views.index,
        search_service=search_service,
        default_query=config.search.default_query,
        default_limit=config.search.default_limit,
    )
    def test_forward_attr_to_default(self):
        default = providers.Configuration()

        provider = providers.Dependency(default=default)
        provider.from_dict({'foo': 'bar'})

        self.assertEqual(default(), {'foo': 'bar'})
class ApplicationContainer(containers.DeclarativeContainer):
    """Application container."""

    config = providers.Configuration()

    configure_logging = providers.Callable(
        logging.basicConfig,
        stream=sys.stdout,
        level=config.log.level,
        format=config.log.format,
    )

    http_client = providers.Factory(http.HttpClient)

    example_monitor = providers.Factory(
        monitors.HttpMonitor,
        http_client=http_client,
        options=config.monitors.example,
    )

    httpbin_monitor = providers.Factory(
        monitors.HttpMonitor,
        http_client=http_client,
        options=config.monitors.httpbin,
    )

    dispatcher = providers.Factory(
        dispatcher.Dispatcher,
        monitors=providers.List(
            example_monitor,
            httpbin_monitor,
        ),
    )
Ejemplo n.º 22
0
class Container(containers.DeclarativeContainer):
    config = providers.Configuration()

    logger = providers.Singleton(LoggingHandler, log_level=config.LOG_LEVEL)

    api_client = providers.Singleton(ApiClient, logger=logger)

    db_handler = providers.Singleton(DbHandler,
                                     logger=logger,
                                     mongo_uri=config.MONGO_URI,
                                     mongo_db_name=config.MONGO_DBNAME)

    bot = providers.Singleton(commands.Bot,
                              command_prefix=config.PREFIX,
                              help_command=None)

    main_cog = providers.Singleton(
        MainCog,
        logger=logger,
        discord_bot=bot,
        db_handler=db_handler,
        api_client=api_client,
    )

    service = providers.Factory(BotService,
                                logger=logger,
                                bot=bot,
                                main_cog=main_cog,
                                discord_token=config.DISCORD_TOKEN)
def test_traverse_overridden_option_2():
    options = {"option2": "option2"}
    config = providers.Configuration()
    config.option1.from_dict(options)

    all_providers = list(config.option1.traverse())

    assert len(all_providers) == 0
    def setUp(self):
        self.config = providers.Configuration(name='config')

        os.environ['CONFIG_TEST_ENV'] = 'test-value'

        _, self.config_file = tempfile.mkstemp()
        with open(self.config_file, 'w') as config_file:
            config_file.write('section1:\n' '  value1: ${CONFIG_TEST_ENV}\n')
    def test_forward_attr_to_overriding(self):
        overriding = providers.Configuration()

        provider = providers.Dependency()
        provider.override(overriding)
        provider.from_dict({'foo': 'bar'})

        self.assertEqual(overriding(), {'foo': 'bar'})
Ejemplo n.º 26
0
class Core(containers.DeclarativeContainer):
    """IoC container of core component providers."""

    config = providers.Configuration('config')

    logger = providers.Singleton(logging.Logger, name='application')

    loop = providers.Singleton(asyncio.get_event_loop)
    def test_traverse_overridden_option_2(self):
        options = {'option2': 'option2'}
        config = providers.Configuration()
        config.option1.from_dict(options)

        all_providers = list(config.option1.traverse())

        self.assertEqual(len(all_providers), 0)
Ejemplo n.º 28
0
class GADMLoaderContainer(containers.DeclarativeContainer):
    """
    DI Container
    """

    config = providers.Configuration()
    disk_cache = providers.Singleton(DiskCacheProvider, disk_cache=config.disk_cache)
    service = providers.Factory(GADMLoaderService, disk_cache=disk_cache)
Ejemplo n.º 29
0
class Container(containers.DeclarativeContainer):

    config = providers.Configuration()

    calculator_factory = providers.Factory(
        Calculator,
        pi=config.pi.as_(decimal.Decimal),
    )
Ejemplo n.º 30
0
class Core(containers.DeclarativeContainer):

    config = providers.Configuration()

    configure_logging = providers.Callable(
        logging.config.dictConfig,
        config=config.logging,
    )