コード例 #1
0
ファイル: injector_test.py プロジェクト: jonblum/injector
def test_child_scope():
    TestKey = Key('TestKey')
    TestKey2 = Key('TestKey2')

    def parent_module(binder):
        binder.bind(TestKey, to=object, scope=singleton)

    def first_child_module(binder):
        binder.bind(TestKey2, to=object, scope=singleton)

    def second_child_module(binder):
        binder.bind(TestKey2, to='marker', scope=singleton)

    injector = Injector(modules=[parent_module])
    first_child_injector = injector.create_child_injector(
        modules=[first_child_module])
    second_child_injector = injector.create_child_injector(
        modules=[second_child_module])

    assert first_child_injector.get(TestKey) is first_child_injector.get(
        TestKey)
    assert first_child_injector.get(TestKey) is second_child_injector.get(
        TestKey)
    assert first_child_injector.get(TestKey2) is not second_child_injector.get(
        TestKey2)
コード例 #2
0
def test_inject_using_key():
    Name = Key('name')
    Description = Key('description')

    class MyModule(Module):
        @provides(Name)
        def provide_name(self):
            return 'Bob'

        @provides(Description)
        @inject(name=Name)
        def provide_description(self, name):
            return '%s is cool!' % name

    assert (Injector(MyModule()).get(Description) == 'Bob is cool!')
コード例 #3
0
ファイル: injector_test.py プロジェクト: jonblum/injector
def test_bind_using_key():
    Name = Key('name')
    Age = Key('age')

    class MyModule(Module):
        @provider
        def provider_name(self) -> Name:
            return 'Bob'

        def configure(self, binder):
            binder.bind(Age, to=25)

    injector = Injector(MyModule())
    assert injector.get(Age) == 25
    assert injector.get(Name) == 'Bob'
コード例 #4
0
ファイル: injector_test.py プロジェクト: jonblum/injector
def test_inject_using_key():
    Name = Key('name')
    Description = Key('description')

    class MyModule(Module):
        @provider
        def provide_name(self) -> Name:
            return 'Bob'

        @provider
        @inject
        def provide_description(self, name: Name) -> Description:
            return '%s is cool!' % name

    assert Injector(MyModule()).get(Description) == 'Bob is cool!'
コード例 #5
0
ファイル: injector_test.py プロジェクト: jonblum/injector
def test_callable_provider_injection():
    Name = Key("Name")
    Message = Key("Message")

    @inject
    def create_message(name: Name):
        return "Hello, " + name

    def configure(binder):
        binder.bind(Name, to="John")
        binder.bind(Message, to=create_message)

    injector = Injector([configure])
    msg = injector.get(Message)
    assert msg == "Hello, John"
コード例 #6
0
def test_multibind() -> None:
    class Handler(ABC):
        pass

    class Handler1(Handler):
        pass

    class Handler2(Handler):
        pass

    class Handler3(Handler):
        def __init__(self, something: str):
            self.something = something

    Handlers = SequenceKey('handlers')
    Something = Key('something')

    def configure(binder: Binder) -> None:
        binder.multibind(Handlers, [Handler1()], scope=singleton)
        binder.multibind(Handlers, [Handler2()], scope=singleton)
        binder.bind(Something, 'hello', scope=singleton)

    class OmgModule(Module):
        @singleton
        @provider
        def handler3(self, something: Something) -> Handlers:
            return [Handler3(cast(str, something))]

    injector = Injector([configure, OmgModule])
    handlers = injector.get(Handlers)
    assert isinstance(handlers[0], Handler1)
    assert isinstance(handlers[1], Handler2)
    assert isinstance(handlers[2], Handler3)
    assert handlers[2].something == 'hello'
コード例 #7
0
ファイル: injector_test.py プロジェクト: jonblum/injector
def test_key_cannot_be_instantiated():
    Interface = Key('Interface')

    with pytest.raises(Exception):
        Interface()

    with pytest.raises(Exception):
        Injector().get(Interface)
コード例 #8
0
ファイル: flags.py プロジェクト: alecthomas/waffle
def FlagKey(name):
    """An injector binding key for an individual flag.

    Use this to inject individual flag values.
    """
    try:
        return _flag_key_cache[name]
    except KeyError:
        key = _flag_key_cache[name] = Key(_flag_key_name(name))
        return key
コード例 #9
0
def test_multibind():
    Names = Key('names')

    def configure_one(binder):
        binder.multibind(Names, to=['Bob'])

    def configure_two(binder):
        binder.multibind(Names, to=['Tom'])

    assert Injector([configure_one, configure_two]).get(Names) == ['Bob', 'Tom']
コード例 #10
0
ファイル: injector_test.py プロジェクト: jonblum/injector
def test_assisted_builder_uses_bindings():
    Interface = Key('Interface')

    def configure(binder):
        binder.bind(Interface, to=NeedsAssistance)

    injector = Injector(configure)
    builder = injector.get(AssistedBuilder[Interface])
    x = builder.build(b=333)
    assert (type(x), x.b) == (NeedsAssistance, 333)
コード例 #11
0
ファイル: injector_test.py プロジェクト: jonblum/injector
def test_child_injector_rebinds_arguments_for_parent_scope():
    I = Key("interface")
    Cls = Key("test_class")

    class A:
        @inject
        def __init__(self, val: I):
            self.val = val

    def configure_parent(binder):
        binder.bind(Cls, to=A)
        binder.bind(I, to="Parent")

    def configure_child(binder):
        binder.bind(I, to="Child")

    parent = Injector(configure_parent)
    assert parent.get(Cls).val == "Parent"
    child = parent.create_child_injector(configure_child)
    assert child.get(Cls).val == "Child"
コード例 #12
0
ファイル: injector_test.py プロジェクト: ahaskell/injector
def test_extends_decorator():
    Names = Key('names')

    class MyModule(Module):
        @extends(Names)
        def bob(self):
            return ['Bob']

        @extends(Names)
        def tom(self):
            return ['Tom']

    assert (Injector(MyModule()).get(Names) == ['Bob', 'Tom'])
コード例 #13
0
ファイル: bus.py プロジェクト: privacy-game/privacy-api
# -*- coding: utf-8 -*-
__author__ = 'Vincent Tertre'

import logging

from injector import inject, Key

logger = logging.getLogger(__name__)
QueryHandlers = Key('query_handlers')
CommandHandlers = Key('command_handlers')


class ExecutionResult(object):
    def __init__(self, response=None, error=None, success=False):
        self.response = response
        self.error = error
        self.success = success

    @staticmethod
    def success(response):
        return ExecutionResult(response=response, success=True)

    @staticmethod
    def error(error):
        return ExecutionResult(error=error)

    def is_success(self):
        return self.success

    def is_error(self):
        return not self.success
コード例 #14
0
ファイル: types.py プロジェクト: u8sand/FAIRshake
UUID = NewType("UUID", str)
HTML = NewType("HTML", str)
ContentType = NewType("ContentType", str)
Timestamp = NewType("Timestamp", str)
# HTTPResponse = NewType("HTTPResponse", str)
T = TypeVar('T')


class HTTPResponse(Generic[T]):
    pass


Interface = NewType("Interface", object)
Implementation = NewType("Implementation", object)
Model = NewType("Model", object)

from injector import Key, MappingKey, SequenceKey

API = Key("API")
APISpec = Key("APISpec")
App = Key("App")
Apps = MappingKey("Apps")
CommandLine = Key("CommandLine")
Config = Key("Config")
Defaults = Key("Defaults")
Environment = Key("Environment")
FlaskApp = Key("FlaskApp")
OIDC = Key("OIDC")
SQLAlchemy = Key("SQLAlchemy")
SQLAlchemyBase = SequenceKey("SQLAlchemyBase")
コード例 #15
0
# -*- coding: utf-8 -*-
from injector import inject, Key

from api.http_utils import WithExponentialBackoff

GoogleDirectoryApiResource = Key(u'google_directory_api_resource')


class DirectoryApiResource(object):
    @inject(api_resource=GoogleDirectoryApiResource)
    def __init__(self, api_resource):
        self.__api_resource = api_resource

    @WithExponentialBackoff
    def list_users(self, **kwargs):
        return self.__api_resource.users().list(**kwargs).execute()
コード例 #16
0
from injector import Key

Count = Key('Count')


class MessageGenerator:
    def __init__(self, message: str) -> None:
        self._message = message

    def make_message(self) -> str:
        return self._message


def get_message(message_generator: MessageGenerator, count: Count):
    return {'message': message_generator.make_message(), 'count': count}
コード例 #17
0
# -*- coding: utf-8 -*-
from injector import inject, Key

from api.http_utils import WithExponentialBackoff

GoogleIAMApiResource = Key(u'google_iam_api_resource')


class IAMApiResource(object):
    @inject(api_resource=GoogleIAMApiResource)
    def __init__(self, api_resource):
        self.__api_resource = api_resource
        self.__keys_resource = api_resource.projects().serviceAccounts().keys()

    @WithExponentialBackoff
    def create_key(self, service_account_resource_id, key_data):
        return self.__keys_resource.create(name=service_account_resource_id,
                                           body=key_data).execute()

    @WithExponentialBackoff
    def delete_key(self, key_resource_id, execute=True):
        request = self.__keys_resource.delete(name=key_resource_id)
        return request.execute() if execute else request

    @WithExponentialBackoff
    def get_key(self, key_resource_id, public_key_type=None):
        return self.__keys_resource.get(
            name=key_resource_id, publicKeyType=public_key_type).execute()

    @WithExponentialBackoff
    def list_keys_of(self, service_account_resource_id, key_types=None):
コード例 #18
0
import logging

from injector import Module, Key, Binder, provides, inject
from logging import Formatter
try:
    from colorlog import ColoredFormatter
except ImportError:
    ColoredFormatter = None

from waffle.flags import Flag, FlagKey, AppStartup

LogLevel = Key('LogLevel')

LOG_LEVELS = [
    'finest', 'finer', 'fine', 'debug', 'info', 'warning', 'error', 'critical'
]


def _configure_logging():
    """Add fine/finer/finest logging."""
    logging.FINE = 7
    logging.FINER = 5
    logging.FINEST = 1

    logging.addLevelName(logging.FINE, 'FINE')
    logging.addLevelName(logging.FINER, 'FINER')
    logging.addLevelName(logging.FINEST, 'FINEST')

    logging.Logger.fine = lambda self, *args, **kwargs: self.log(
        logging.FINE, *args, **kwargs)
    logging.Logger.finer = lambda self, *args, **kwargs: self.log(
コード例 #19
0
#ASFER - Software for Mining Large Datasets
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
#--------------------------------------------------------------------------------------------------------
#Copyright (C):
#Srinivasan Kannan (alias) Ka.Shrinivaasan (alias) Shrinivas Kannan
#Ph: 9791499106, 9003082186
#Krishna iResearch Open Source Products Profiles:
#http://sourceforge.net/users/ka_shrinivaasan,
#https://github.com/shrinivaasanka,
#https://www.openhub.net/accounts/ka_shrinivaasan
#Personal website(research): https://sites.google.com/site/kuja27/
#emails: [email protected], [email protected],
#[email protected]
#-----------------------------------------------------------------------------------------------------------------------------------

from injector import Module, Key, provides, Injector, inject, singleton

Configuration=Key('configuration')
class MongoDB_Configuration(Module):
	def configure(self, binder):
		binder.bind(Configuration, to={'database':'asfer_database','collection':'asfer_collection'}, scope=singleton)
コード例 #20
0
ファイル: interfaces.py プロジェクト: edenist/hal
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

from injector import Key

Configuration = Key('Configuration')
コード例 #21
0
from injector import Key

App = Key('application')
Configuration = Key('configuration')
コード例 #22
0
import pymysql
import os
from injector import Key, Module, provider, singleton
from collections import namedtuple

database_configurations = Key('db_config')

def get_configurations(binder):
    """ Add connection attributes """

    Configuration = namedtuple('Configuration', 'host user password database')
    configt = Configuration(host = os.getenv('host'), user = os.getenv('user'), password = os.getenv('password'), database=os.getenv('database'))
    binder.bind(database_configurations, to=configt, scope=singleton)

class MysqlConnection(Module):
    """ connection class """

    @provider
    @singleton
    def connect(self, configuration: database_configurations) -> pymysql.connect:
        """ Connect to the db """ 
        connection = pymysql.connect(host=configuration.host,
                                     password = configuration.password,
                                     user = configuration.user,
                                     database = configuration.database,
                                     cursorclass = pymysql.cursors.DictCursor,
                                     charset = 'utf8mb4'
                                    )
        return connection
コード例 #23
0
ファイル: plugin.py プロジェクト: edenist/hal
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

from imp import load_source
from os import environ, listdir
from os.path import isfile, join

from injector import inject, Key, Module, provides, singleton

from hal import PROJECT_ROOT

PluginDirectories = Key('PluginDirectories')


class PluginModuleCollector(object):
    @inject(directories=PluginDirectories)
    def collect(self, directories):
        modules = []

        for directory in directories:
            for name in listdir(directory):
                full_name = join(directory, name)
                if full_name.endswith('.py') and isfile(full_name):
                    module = load_source(full_name.replace('/', ''), full_name)
                    if hasattr(module, 'plugin'):
                        modules.append(module)

        return modules


class PluginModule(Module):
コード例 #24
0
from injector import inject, Injector, provider, Module, Key, singleton
import sqlite3


class RequestHandler:
    @inject
    def __init__(self, db: sqlite3.Connection):
        self._db = db

    def get(self):
        cursor = self._db.cursor()
        cursor.execute('SELECT key, value FROM data ORDER by key')
        return cursor.fetchall()


Configuration = Key("configuration")


def configuration_for_testing(binder):
    configuration = {"db_connection_string": ":memory:"}
    binder.bind(Configuration, to=configuration, scope=singleton)


class DatabaseModule(Module):
    @singleton
    @provider
    def provide_sqlite_connection(
            self, configuration: Configuration) -> sqlite3.Connection:
        conn = sqlite3.connect(configuration["db_connection_string"])
        cursor = conn.cursor()
        cursor.execute(
コード例 #25
0
ファイル: clastic.py プロジェクト: alecthomas/waffle
from injector import Injector, Module, Scope, ScopeDecorator, InstanceProvider, \
    Key, Binder, SequenceKey, MappingKey, provides, inject, singleton
from clastic import Application, Middleware as WebMiddleware, Request, render_basic
from clastic.middleware.session import CookieSessionMiddleware, JSONCookie
from werkzeug.local import Local, LocalManager

from waffle.flags import Flag, Flags
from waffle.util import parse_reltime


Routes = SequenceKey('Routes')
Middlewares = SequenceKey('Middlewares')
Resources = MappingKey('Resources')
ErrorHandlers = MappingKey('ErrorHandlers')
RenderFactory = Key('RenderFactory')
SessionCookie = JSONCookie


_routes = []


class RoutesModule(Module):
    """Bind a set of manually defined routes."""

    def __init__(self, routes):
        self._routes = routes or []

    def configure(self, binder):
        binder.multibind(Routes, to=self._routes)
コード例 #26
0
# -*- coding: utf-8 -*-

from abc import ABCMeta, abstractmethod

from injector import Key

ErrorResolvers = Key(u'error_resolvers')


class ErrorResolver(object):
    __metaclass__ = ABCMeta

    def can_resolve(self, error):
        error_type = error.__class__ if error else None
        return error is not None and error_type is not None and self.error_type == error_type

    @property
    @abstractmethod
    def error_type(self):
        raise NotImplementedError

    @property
    @abstractmethod
    def status(self):
        raise NotImplementedError

    @abstractmethod
    def representation(self, error):
        return None
コード例 #27
0
ファイル: di.py プロジェクト: Raiu/gkraken
from typing import Optional
from gi.repository import Gtk
from injector import Module, provider, singleton, Injector, Key
from liquidctl.cli import find_all_supported_devices
from liquidctl.driver.kraken_two import KrakenTwoDriver
from peewee import SqliteDatabase
from rx.disposables import CompositeDisposable
from rx.subjects import Subject

from gkraken.conf import APP_PACKAGE_NAME, APP_MAIN_UI_NAME, APP_DB_NAME, APP_EDIT_SPEED_PROFILE_UI_NAME, \
    APP_PREFERENCES_UI_NAME
from gkraken.util.path import get_data_path, get_config_path

LOG = logging.getLogger(__name__)

SpeedProfileChangedSubject = Key("SpeedProfileChangedSubject")
SpeedStepChangedSubject = Key("SpeedStepChangedSubject")
MainBuilder = Key(APP_MAIN_UI_NAME)
EditSpeedProfileBuilder = Key(APP_EDIT_SPEED_PROFILE_UI_NAME)
PreferencesBuilder = Key(APP_PREFERENCES_UI_NAME)


# pylint: disable=no-self-use
class ProviderModule(Module):
    @singleton
    @provider
    def provide_main_builder(self) -> MainBuilder:
        LOG.debug("provide Gtk.Builder")
        builder = Gtk.Builder()
        builder.set_translation_domain(APP_PACKAGE_NAME)
        builder.add_from_file(get_data_path(APP_MAIN_UI_NAME))
コード例 #28
0
ファイル: inject5.py プロジェクト: macinjoke/various
from injector import Key, ClassAssistedBuilder, AssistedBuilder, Injector, inject

DB = Key('DB')


class DBImplementation:
    def __init__(self, uri):
        pass


def configure(binder):
    binder.bind(DB, to=DBImplementation)


if __name__ == '__main__':

    # injector = Injector()
    # builder = injector.get(ClassAssistedBuilder[UserUpdater])
    # user = User('John')
    # user_updater = builder.build(user=user)

    print("aaa")
    injector = Injector(configure)
    builder = injector.get(AssistedBuilder[DB])
    # print(isinstance(builder.build(uri='x'), DBImplementation))
コード例 #29
0
from injector import Key

AccountRepository = Key('account_repository')
コード例 #30
0
ファイル: base.py プロジェクト: xrloong/Yong8
import unittest

from injector import Key

GlyphSolver = Key('GlyphSolver')

class BaseTestCase(unittest.TestCase):
	def setUp(self):
		import warnings
		warnings.filterwarnings("ignore", category=ResourceWarning)
		warnings.filterwarnings("ignore", category=DeprecationWarning)

	def tearDown(self):
		pass

	def getInjector(self):
		from injector import Injector
		from yong8.shape import ConstraintShape
		from .injection import DrawingModule
		from .injection import FactoryModule

		from xrsolver.solver.gekko import Solver

		def configure(binder):
			binder.bind(GlyphSolver, to=Solver())

		return Injector([configure, DrawingModule(), FactoryModule()])

	def assertSequenceAlmostEqual(self, seq1, seq2):
		def almost_equal(value_1, value_2):
			return self.assertAlmostEqual(value_1, value_2)