コード例 #1
0
ファイル: injector_test.py プロジェクト: ownermz/injector
def test_deprecated_module_configure_injection():
    class Test(Module):
        @inject
        def configure(self, binder, name: int):
            pass

    class Test2(Module):
        @inject
        def __init__(self, name: int):
            pass

    @inject
    def configure(binder, name: int):
        pass

    for module in [Test, Test2, configure, Test()]:
        with warnings.catch_warnings(record=True) as w:
            print(module)
            Injector(module)
        assert len(w) == 1, w
コード例 #2
0
ファイル: injector_test.py プロジェクト: ahmedosman1/injector
def test_class_assisted_builder_of_partially_injected_class():
    class A(object):
        pass

    class B(object):
        @inject(a=A, b=str)
        def __init__(self, a, b):
            self.a = a
            self.b = b

    class C(object):
        @inject(a=A, builder=ClassAssistedBuilder[B])
        def __init__(self, a, builder):
            self.a = a
            self.b = builder.build(b='C')

    c = Injector().get(C)
    assert isinstance(c, C)
    assert isinstance(c.b, B)
    assert isinstance(c.b.a, A)
コード例 #3
0
def test_dataclass_integration_works():
    import dataclasses

    # Python 3.6+-only syntax below
    exec(
        """
@inject
@dataclasses.dataclass
class Data:
    name: str
    """,
        locals(),
        globals(),
    )

    def configure(binder):
        binder.bind(str, to='data')

    injector = Injector([configure])
    assert injector.get(Data).name == 'data'
コード例 #4
0
def test_child_injector_rebinds_arguments_for_parent_scope():
    class Cls:
        val = ""

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

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

    def configure_child(binder):
        binder.bind(str, 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"
コード例 #5
0
def test_more_useful_exception_is_raised_when_parameters_type_is_any():
    @inject
    def fun(a: Any) -> None:
        pass

    injector = Injector()

    # This was the exception before:
    #
    # TypeError: Cannot instantiate <class 'typing.AnyMeta'>
    #
    # Now:
    #
    # injector.CallError: Call to AnyMeta.__new__() failed: Cannot instantiate
    #   <class 'typing.AnyMeta'> (injection stack: ['injector_test_py3'])
    #
    # In this case the injection stack doesn't provide too much information but
    # it quickly gets helpful when the stack gets deeper.
    with pytest.raises((CallError, TypeError)):
        injector.call_with_injection(fun)
コード例 #6
0
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)
コード例 #7
0
ファイル: injector_test.py プロジェクト: ahaskell/injector
    def setup(self):
        class A(object):
            counter = 0

            def __init__(self):
                A.counter += 1

        @inject(a=A)
        class B(object):
            pass

        @inject(a=A)
        class C(object):
            def __init__(self, noninjectable):
                self.noninjectable = noninjectable

        self.injector = Injector()
        self.A = A
        self.B = B
        self.C = C
コード例 #8
0
def test_class_assisted_builder_of_partially_injected_class():
    class A:
        pass

    class B:
        @inject
        def __init__(self, a: A, b: str):
            self.a = a
            self.b = b

    class C:
        @inject
        def __init__(self, a: A, builder: ClassAssistedBuilder[B]):
            self.a = a
            self.b = builder.build(b='C')

    c = Injector().get(C)
    assert isinstance(c, C)
    assert isinstance(c.b, B)
    assert isinstance(c.b.a, A)
コード例 #9
0
    def get_polygon(self, arg_string):
        """Get class using reflection and Dependency Injection with API Injector"""

        self.parser.set_string(arg_string)
        arguments = self.parser.argument_parser().get_arguments()

        # instead of abstract fabric have used reflection and assential injection
        TypePolygon = getattr(importlib.import_module("models.type_polygons"),
                              arguments[0])
        InjectedPolygon = BoundKey(TypePolygon,
                                   x=InstanceProvider(arguments[1]),
                                   y=InstanceProvider(arguments[2]),
                                   side=InstanceProvider(arguments[3]),
                                   n=InstanceProvider(arguments[4]))

        injector = Injector()
        polygon = injector.get(InjectedPolygon)

        self.notify_observer(polygon)
        return polygon
コード例 #10
0
def test_child_scope():
    TestKey = NewType('TestKey', str)
    TestKey2 = NewType('TestKey2', str)

    def parent_module(binder):
        binder.bind(TestKey, to='in parent', scope=singleton)

    def first_child_module(binder):
        binder.bind(TestKey2, to='in first child', scope=singleton)

    def second_child_module(binder):
        binder.bind(TestKey2, to='in second child', 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)
コード例 #11
0
async def main():
    port = 56153
    base = URL("http://localhost").with_port(port)
    config = Config.withOverrides({
        Setting.DRIVE_AUTHORIZE_URL: str(base.with_path("o/oauth2/v2/auth")),
        Setting.AUTHENTICATE_URL: str(base.with_path("drive/authorize")),
        Setting.DRIVE_TOKEN_URL: str(base.with_path("token")),
        Setting.DRIVE_REFRESH_URL: str(base.with_path("oauth2/v4/token")),
        Setting.INGRESS_PORT: 56152
    })
    injector = Injector(SimServerModule(config))
    server = injector.get(SimulationServer)

    # start the server
    runner = aiohttp.web.AppRunner(server.createApp())
    await runner.setup()
    site = aiohttp.web.TCPSite(runner, "0.0.0.0", port=port)
    await site.start()
    print("Server started on port " + str(port))
    print("Open a browser at http://localhost:" + str(port))
コード例 #12
0
ファイル: injector_test.py プロジェクト: ownermz/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")
コード例 #13
0
ファイル: injector_test.py プロジェクト: ownermz/injector
def test_that_injection_is_lazy():
    class Interface:
        constructed = False

        def __init__(self):
            Interface.constructed = True

    class A:
        @inject
        def __init__(self, i: Interface):
            self.i = i

    def configure(binder):
        binder.bind(Interface)
        binder.bind(A)

    injector = Injector(configure)
    assert not (Interface.constructed)
    injector.get(A)
    assert (Interface.constructed)
コード例 #14
0
ファイル: __init__.py プロジェクト: alancrisp/scores
def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev'
    )

    app.config['MYSQL_HOST'] = os.environ.get('DB_HOST')
    app.config['MYSQL_USER'] = os.environ.get('DB_USER')
    app.config['MYSQL_PASSWORD'] = os.environ.get('DB_PASSWORD')
    app.config['MYSQL_DB'] = os.environ.get('DB_DATABASE')
    app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    from . import course
    from . import event
    from . import player
    app.register_blueprint(course.bp)
    app.register_blueprint(event.bp)
    app.register_blueprint(player.bp)

    from scores.repo.eventrepo import EventRepo

    @inject
    @app.route('/')
    def home(repo: EventRepo):
        return event.events(repo)

    from .servicemodule import ServiceModule
    injector = Injector([ServiceModule(app)])
    FlaskInjector(app=app, injector=injector)

    return app
コード例 #15
0
def init_app(config):
    app = flask.Flask(__name__)

    app.config.from_object(config)

    app.json_encoder = FlaskCustomJSONEncoder

    db.init_app(app)

    if not app.testing:
        logging.basicConfig(level=logging.INFO)

    app.register_blueprint(blueprint=blueprint, url_prefix='/')

    # Sentry - only for production

    # Todo uncomment this if you have a sentry DSN
    # if not app.debug and not app.testing and 'SENTRY_DSN' in app.config:
    #     from raven.contrib.flask import Sentry
    #     Sentry(app)

    @app.errorhandler(ClientException)
    def handle_client_errors(error):
        response = flask.jsonify(error.to_dict())
        response.status_code = error.status_code
        return response

    with app.app_context():
        db.create_all()

        my_injector = Injector([
            ServiceModule,
            FactoryModule,
            PersonRepositoryModule
        ])

        FlaskInjector(app=app, injector=my_injector)

    # No configuration after injection

    return app
コード例 #16
0
ファイル: injector_test.py プロジェクト: jonblum/injector
def test_cyclic_dependencies():
    class Interface:
        pass

    class A:
        @inject
        def __init__(self, i: Interface):
            self.i = i

    class B:
        @inject
        def __init__(self, a: A):
            self.a = a

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

    injector = Injector(configure)
    with pytest.raises(CircularDependency):
        injector.get(A)
コード例 #17
0
def main():
    db_path = os.path.join(
        os.path.dirname(os.path.realpath(__file__)) + os.sep + 'app.db')

    app = Flask(__name__)
    app.secret_key = os.getenv('SECRET_KEY', 'b3D$EJAQ4g91U8UPqwZ4yaaSoAsH!V')
    app.register_blueprint(main_blueprint, url_prefix='/')
    app.register_blueprint(config_blueprint, url_prefix='/config')
    app.register_blueprint(config_account_blueprint,
                           url_prefix='/config/account')
    app.register_blueprint(config_plan_blueprint, url_prefix='/config/plan')
    app.register_blueprint(config_settings_blueprint,
                           url_prefix='/config/settings')
    app.config.update(SQLALCHEMY_DATABASE_URI='sqlite:///{0}'.format(db_path),
                      SQLALCHEMY_TRACK_MODIFICATIONS=False)
    app.debug = os.getenv('DEBUGGING', 'N') == 'Y'

    injector = Injector([AppModule(app)])
    FlaskInjector(app=app, injector=injector)

    app.run()
コード例 #18
0
def test_cyclic_dependencies():
    class Interface(object):
        pass

    class A(object):
        @inject(i=Interface)
        def __init__(self, i):
            self.i = i

    class B(object):
        @inject(a=A)
        def __init__(self, a):
            self.a = a

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

    injector = Injector(configure)
    with pytest.raises(CircularDependency):
        injector.get(A)
コード例 #19
0
async def injector(cleandir, server_url, ports):
    drive_creds = Creds(FakeTime(), "test_client_id", None,
                        "test_access_token", "test_refresh_token")
    with open(os.path.join(cleandir, "secrets.yaml"), "w") as f:
        f.write("for_unit_tests: \"password value\"\n")

    with open(os.path.join(cleandir, "credentials.dat"), "w") as f:
        f.write(json.dumps(drive_creds.serialize()))

    config = Config.withOverrides({
        Setting.DRIVE_URL: server_url,
        Setting.HASSIO_URL: server_url + "/",
        Setting.HOME_ASSISTANT_URL: server_url + "/core/api/",
        Setting.AUTHENTICATE_URL: server_url + "/drive/authorize",
        Setting.DRIVE_REFRESH_URL: server_url + "/oauth2/v4/token",
        Setting.DRIVE_AUTHORIZE_URL: server_url + "/o/oauth2/v2/auth",
        Setting.DRIVE_TOKEN_URL: server_url + "/token",
        Setting.REFRESH_URL: server_url + "/drive/refresh",
        Setting.ERROR_REPORT_URL: server_url + "/logerror",
        Setting.HASSIO_TOKEN: "test_header",
        Setting.SECRETS_FILE_PATH: "secrets.yaml",
        Setting.CREDENTIALS_FILE_PATH: "credentials.dat",
        Setting.FOLDER_FILE_PATH: "folder.dat",
        Setting.RETAINED_FILE_PATH: "retained.json",
        Setting.ID_FILE_PATH: "id.json",
        Setting.STOP_ADDON_STATE_PATH: "stop_addon.json",
        Setting.INGRESS_TOKEN_FILE_PATH: "ingress.dat",
        Setting.DEFAULT_DRIVE_CLIENT_ID: "test_client_id",
        Setting.DEFAULT_DRIVE_CLIENT_SECRET: "test_client_secret",
        Setting.BACKUP_DIRECTORY_PATH: cleandir,
        Setting.PORT: ports.ui,
        Setting.INGRESS_PORT: ports.ingress
    })

    # PROBLEM: Something in uploading snapshot chunks hangs between the client and server, so his keeps tests from
    # taking waaaaaaaay too long.  Remove this line and the @pytest.mark.flaky annotations once the problem is identified.
    config.override(Setting.GOOGLE_DRIVE_TIMEOUT_SECONDS, 5)

    # logging.getLogger('injector').setLevel(logging.DEBUG)
    return Injector([BaseModule(config), TestModule(ports)])
コード例 #20
0
  def main(argv: Any):
    """Stuff to setup after absl is run."""
    setup_logging(FLAGS.logtype)

    try:
      modules = modules_func()
      modules.insert(0, EnvironmentModule)
      modules.insert(0, DecoratorProcessorModule)
      modules.insert(0, SignalHandlerModule)
      modules.insert(0, ExecuteModule)
      modules.insert(0, MetriczPageModule)
      injector = Injector(modules=modules, auto_bind=False)

      env = injector.get(Environment)
      log.info(f'Application running with environment {env.name}')

      bindings = get_bindings(injector)
      for binding in bindings:
        try:
          log.debug(f'Resolving binding for {binding}')
          injector.get(binding)
        except:
          log.exception(
              f'Could not start application: Error resolving binding {binding}')
          return 1

      # Run all decorator processors.
      decorator_processor_runner = injector.get(DecoratorProcessorRunner)
      decorator_processor_runner.run_processors()

      # Run all execute methods and wait until all finished.
      execute_processor = injector.get(ExecuteProcessor)
      execute_processor.run_and_wait()

      log.info('Application finished successfully')
      return 0
    except:
      log.exception('Application finished with an error')
      return 1
コード例 #21
0
ファイル: injector_test.py プロジェクト: jonblum/injector
def test_providerof():
    counter = [0]

    def provide_str():
        counter[0] += 1
        return 'content'

    def configure(binder):
        binder.bind(str, to=provide_str)

    injector = Injector(configure)

    assert counter[0] == 0

    provider = injector.get(ProviderOf[str])
    assert counter[0] == 0

    assert provider.get() == 'content'
    assert counter[0] == 1

    assert provider.get() == injector.get(str)
    assert counter[0] == 3
コード例 #22
0
ファイル: injector_test.py プロジェクト: ahaskell/injector
def test_injecting_undecorated_class_with_missing_dependencies_raises_the_right_error():
    class A(object):
        def __init__(self, parameter):
            pass

    class B(object):
        @inject(a=A)
        def __init__(self, a):
            pass

    injector = Injector()
    try:
        injector.get(B)
    except CallError as ce:
        function = A.__init__

        # Python 3 compatibility
        try:
            function = function.__func__
        except AttributeError:
            pass
        assert (ce.args[1] == function)
コード例 #23
0
class TestTempSource(TestCase):
    injector = Injector([configure_test])
    factory = injector.get(ProbeTempSourceFactory)

    def test_nickname(self):
        source = self.factory.get_temp_source("room")
        self.assertEqual(source.get_name(), tempSource.PROBE_PREFIX + "room")
        source.set_nickname("nick")
        self.assertEqual(source.get_display_name(), "nick")

    def test_filename(self):
        api = self.injector.get(ProbeApi)
        source2 = tempSource.TempSource(api, "path/to/a/filename2")
        self.assertEqual(source2.get_display_name(),
                         tempSource.PROBE_PREFIX + "a")

        source3 = tempSource.TempSource(
            api, "/sys/bus/w1/devices/uniquename/w1_slave")
        self.assertEqual(source3.get_display_name(),
                         tempSource.PROBE_PREFIX + "uniquename")

        source4 = tempSource.TempSource(
            api, "sys/bus/w1/devices/28-041651652cff/w1_slave")
        self.assertEqual(source4.get_display_name(),
                         tempSource.PROBE_PREFIX + "28-041651652cff")

    def test_equality(self):
        api = self.injector.get(ProbeApi)
        source1 = tempSource.TempSource(api, "path/to/a/filename2")
        source2 = tempSource.TempSource(api, "path/to/a/filename2")
        source1.set_primary(True)

        self.assertEqual(source1, source2)

    def test_temp(self):
        api = self.injector.get(ProbeApi)
        source1 = tempSource.TempSource(api, "brew")
        self.assertEqual(
            type(source1.get_temperature_measurement().measurement_amt), float)
コード例 #24
0
def main():
    global agents

    # This file is set up to use different models and datasets.
    dataset = 'offensive'
    model_type = 'nb'

    assert dataset in datasets
    assert model_type in models

    train_size = datasets[dataset]['train_size']
    test_size = datasets[dataset]['test_size']
    if train_size is None:
        init_train_data_portion = 0.08
    else:
        init_train_data_portion = 100 / train_size

    # No caller (assume free to call).
    agents = agents[:-1]

    # Set up the data, model, and incentive mechanism.
    inj = Injector([
        DefaultCollaborativeTrainerModule,
        datasets[dataset]['module'],
        MurmurHash3Module,
        LoggingModule,
        models[model_type]['module'],
        StakeableImModule,
    ])
    s = inj.get(Simulator)

    # Start the simulation.
    s.simulate(
        agents,
        baseline_accuracy=models[model_type]['baseline_accuracy'].get(dataset),
        init_train_data_portion=init_train_data_portion,
        train_size=train_size,
        test_size=test_size,
        filename_indicator=f"{dataset}-{model_type}")
コード例 #25
0
def assist():
    app = Flask(__name__)
    module = AppModule()
    injector = Injector([module])
    assist = Assistant(app, project_id="test-project-id", injector=injector)

    @assist.action("simple_intent")
    def simple_intent():
        speech = "Yes"
        return ask(speech)

    @inject
    @assist.action("simple_intent_with_inject")
    def simple_intent_with_inject(speech: str):
        return ask(speech)

    @inject
    @assist.action("simple_intent_with_inject_and_param")
    def simple_intent_with_inject_and_param(speech: str, param):
        return ask(param + "." + speech)

    @inject
    @assist.action("intent_with_injects_and_2_param")
    def intent_with_injects_and_2_param(speech: str, p1, p2, i: int):
        return ask(speech + ":" + p1 + ":" + p2 + ":" + str(i))

    @assist.action("add_context_1")
    def add_context():
        speech = "Adding context to context_out"
        manager.add("context_1")
        return ask(speech)

    @assist.context("context_1")
    @assist.action("intent_with_context_injects_params")
    @inject
    def intent_with_context_injects_params(speech: str, p1, p2, i: int):
        return ask("context_1:" + speech + ":" + p1 + ":" + p2 + ":" + str(i))

    return assist
コード例 #26
0
    def setUp(self):

        def configure(binder):
            PROVIDER = "sqlite"
            FILE_NAME = os.path.join("..", "..", "data", "database-test.sqlite")
            create_db = True

            args = {
                "provider": PROVIDER,
                "filename": FILE_NAME,
                "create_db": create_db
            }

            db = Database(**args)
            db.model.generate_mapping(create_tables=True)
            binder.bind(Database, to=db, scope=singleton)

            for service in SERVICES:
                binder.bind(service, scope=singleton)

        self.injector = Injector(modules=[configure])
        self.db = self.injector.get(Database)
コード例 #27
0
ファイル: injector_test.py プロジェクト: jonblum/injector
def test_forward_references_in_annotations_are_handled():
    # See https://www.python.org/dev/peps/pep-0484/#forward-references for details
    def configure(binder):
        binder.bind(X, to=X('hello'))

    @inject
    def fun(s: 'X') -> 'X':
        return s

    # The class needs to be module-global in order for the string -> object
    # resolution mechanism to work. I could make it work with locals but it
    # doesn't seem worth it.
    global X

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

    try:
        injector = Injector(configure)
        injector.call_with_injection(fun).message == 'hello'
    finally:
        del X
コード例 #28
0
ファイル: __main__.py プロジェクト: iomegak12/sislcrmsystem
def main():
    def configure(binder):
        binder.bind(CustomerService, to=CustomerService())
        binder.bind(OrderService, to=OrderService())

    try:
        injector = Injector([configure])
        controller = injector.get(CRMSystemServiceController)

        if controller is None:
            raise Exception("Invalid Controller Impl Specified")

        customers, orders = controller.process()

        print(TableGenerator.get_customer_table(customers))
        print('\n')
        print(TableGenerator.get_orders_table(orders))
    except CRMSystemError as error:
        print('Application Error Occurred ... {0}'.format(error.__str__()))
    except Exception as error:
        print('General Error Occurred!')
    except:
        print('Unknown Error Occurred!')
コード例 #29
0
def test_injection_works_in_presence_of_return_value_annotation():
    # Code with PEP 484-compatible type hints will have __init__ methods
    # annotated as returning None[1] and this didn't work well with Injector.
    #
    # [1] https://www.python.org/dev/peps/pep-0484/#the-meaning-of-annotations

    class A:
        def __init__(self, s: str) -> None:
            self.s = s

    def configure(binder):
        binder.bind(str, to='this is string')

    injector = Injector([configure], use_annotations=True)

    # Used to fail with:
    # injector.UnknownProvider: couldn't determine provider for None to None
    a = injector.get(A)

    # Just a sanity check, if the code above worked we're almost certain
    # we're good but just in case the return value annotation handling changed
    # something:
    assert a.s == 'this is string'
コード例 #30
0
ファイル: injector_test.py プロジェクト: jonblum/injector
def test_special_interfaces_work_with_auto_bind_disabled():
    class InjectMe:
        pass

    def configure(binder):
        binder.bind(InjectMe, to=InstanceProvider(InjectMe()))

    injector = Injector(configure, auto_bind=False)

    # This line used to fail with:
    # Traceback (most recent call last):
    #   File "/projects/injector/injector_test.py", line 1171,
    #   in test_auto_bind_disabled_regressions
    #     injector.get(ProviderOf(InjectMe))
    #   File "/projects/injector/injector.py", line 687, in get
    #     binding = self.binder.get_binding(None, key)
    #   File "/projects/injector/injector.py", line 459, in get_binding
    #     raise UnsatisfiedRequirement(cls, key)
    # UnsatisfiedRequirement: unsatisfied requirement on
    # <injector.ProviderOf object at 0x10ff01550>
    injector.get(ProviderOf[InjectMe])

    # This used to fail with an error similar to the ProviderOf one
    injector.get(ClassAssistedBuilder[InjectMe])