Ejemplo n.º 1
0
def test_deep_clone():
    world.test.singleton("test", 1)

    with world.test.clone(keep_singletons=True):
        with world.test.clone(keep_singletons=False):
            with pytest.raises(DependencyNotFoundError):
                world.get("test")
Ejemplo n.º 2
0
def test_implementation_permanent_singleton(service: ServiceProvider,
                                            singleton: bool, permanent: bool):
    scope = Scope.singleton() if singleton else None
    choice = 'a'

    def implementation():
        return dict(a=A, b=B)[choice]

    service.register(A, scope=scope)
    service.register(B, scope=scope)
    indirect = IndirectProvider()
    impl = indirect.register_implementation(Interface,
                                            implementation,
                                            permanent=permanent)

    instance = world.test.maybe_provide_from(indirect, impl).unwrapped
    assert isinstance(instance, A)
    assert (instance is world.get(A)) is singleton
    assert world.test.maybe_provide_from(
        indirect, impl).is_singleton() is (singleton and permanent)

    choice = 'b'
    assert implementation() == B
    assert world.test.maybe_provide_from(
        indirect, impl).is_singleton() is (singleton and permanent)
    instance = world.test.maybe_provide_from(indirect, impl).unwrapped
    if permanent:
        assert isinstance(instance, A)
        assert (instance is world.get(A)) is singleton
    else:
        assert isinstance(instance, B)
        assert (instance is world.get(B)) is singleton
Ejemplo n.º 3
0
def test_simple():
    class A(Service):
        pass

    assert isinstance(world.get(A), A)
    # singleton by default
    assert world.get(A) is world.get(A)
Ejemplo n.º 4
0
def test_copy(provider: ServiceProvider, keep_singletons_cache: bool,
              scope: Scope):
    class C:
        pass

    world.test.singleton('factory', lambda: C())
    provider.register(A, scope=scope)

    cloned = provider.clone(keep_singletons_cache)
    if keep_singletons_cache:
        with world.test.clone(keep_singletons=True):
            assert isinstance(
                world.test.maybe_provide_from(cloned, A).unwrapped, A)
    else:
        with world.test.clone(keep_singletons=False):
            assert isinstance(
                world.test.maybe_provide_from(cloned, A).unwrapped, A)

    class D:
        pass

    class E:
        pass

    # changing original does not change cloned
    provider.register(D, scope=scope)
    assert isinstance(world.get(D), D)
    assert world.test.maybe_provide_from(cloned, D) is None

    # changing cloned does not change original
    cloned.register(E, scope=scope)
    assert isinstance(world.test.maybe_provide_from(cloned, E).unwrapped, E)
    with pytest.raises(DependencyNotFoundError):
        world.get(E)
Ejemplo n.º 5
0
def handle_verify_confirm(self, organization_name: str, request_uid: str,
                          connection_id: str, presentation_id: str,
                          request_data: dict):
    logger.info(
        "REDIS: handle_verify_confirm for request_uid: %s, connection_id: %s, presentation_id: %s ",
        request_uid, connection_id, presentation_id)
    try:
        description_handler = world.get(DescriptionHandler)
        notification_service = world.get(NotificationService)
        handler_manager: OrganizationHandlerManager = world.get(
            OrganizationHandlerManager)
        org_handler: OrganizationAbstractHandler = handler_manager.get_organization_handler(
            organization_name)
        # org_handler = VipMobileHandler()
        if org_handler:
            org_handler.handle_confirm_verify(request_uid, connection_id,
                                              presentation_id, request_data)
        return "OK"
    except Exception as ex:
        logger.error("Exception during handle_verify_confirm task: " + str(ex))
        if connection_id and presentation_id:
            user_connection = user_entity.get_user_connection(
                connection_id=connection_id)
            descriptions = description_handler.get_descriptions(
                DescriptionMessagesCodes.PROCESSING_ERROR)
            notification_service.send_verify_response(user_connection,
                                                      presentation_id,
                                                      descriptions,
                                                      VerifyResult.KO)

        traceback.print_exception(type(ex), ex, ex.__traceback__)
        return "An exception occurred"
Ejemplo n.º 6
0
def test_double_injection(wire):
    @wire(methods=['f'])
    class A:
        @inject(auto_provide=True)  # auto_provide to force injection
        def f(self, x: MyService):
            return x

    assert A().f() is world.get(MyService)

    with pytest.raises(DoubleInjectionError):
        @wire(methods=['f'], raise_on_double_injection=True)
        class B:
            @inject(auto_provide=True)  # auto_provide to force injection
            def f(self, x: MyService):
                return x

    @wire()
    class C:
        @inject(auto_provide=True)  # auto_provide to force injection
        def f(self, x: MyService):
            return x

    assert C().f() is world.get(MyService)

    with pytest.raises(DoubleInjectionError):
        @wire(raise_on_double_injection=True)
        class D:
            @inject(auto_provide=True)  # auto_provide to force injection
            def f(self, x: MyService):
                return x
Ejemplo n.º 7
0
def test_lazy(provider: FactoryProvider):
    world.test.singleton('A', build)
    factory_id = provider.register(A,
                                   factory_dependency='A',
                                   scope=Scope.singleton())
    assert isinstance(world.get(factory_id), A)
    # singleton
    assert world.get(factory_id) is world.get(factory_id)
Ejemplo n.º 8
0
def test_register_simple():
    @service
    class A:
        pass

    assert isinstance(world.get(A), A)
    # singleton by default
    assert world.get(A) is world.get(A)
Ejemplo n.º 9
0
def test_default(class_builder: F):
    dummy = class_builder(DEFAULT_WIRING)()
    assert dummy.a is world.get(A)
    assert dummy.b is world.get(B)

    (a, b) = dummy.method_AB()
    assert a is None
    assert b is None
Ejemplo n.º 10
0
def test_singleton():
    with world.test.empty():
        world.test.singleton("singleton", 12342)
        assert world.get("singleton") == 12342

        world.test.singleton({"singleton2": 89, "singleton3": 123})
        assert world.get("singleton2") == 89
        assert world.get("singleton3") == 123
Ejemplo n.º 11
0
def test_factory_no_scope():
    with world.test.empty():

        @world.test.factory(Service, singleton=False)
        def build():
            return Service()

        assert world.get(Service) is not world.get(Service)
Ejemplo n.º 12
0
def test_container_lock():
    from ..test_thread_safety import ThreadSafetyTest

    with world.test.empty():
        failures = []

        @world.provider
        class A(Provider):
            def exists(self, dependency: Hashable) -> bool:
                return dependency == 'a'

            def provide(self, dependency: Hashable,
                        container: Container) -> DependencyValue:
                ThreadSafetyTest.check_locked(failures)
                return DependencyValue('a')

            def change_state(self):
                with self._container_lock():
                    ThreadSafetyTest.check_locked(failures)

        @world.provider
        class B(Provider):
            def exists(self, dependency: Hashable) -> bool:
                return dependency == 'b'

            def provide(self, dependency: Hashable,
                        container: Container) -> DependencyValue:
                ThreadSafetyTest.check_locked(failures)
                return DependencyValue('b')

            def change_state(self):
                with self._container_lock():
                    ThreadSafetyTest.check_locked(failures)

        a = world.get[A]()
        b = world.get[B]()
        actions = [
            lambda: a.change_state(), lambda: world.get('a'),
            lambda: b.change_state(), lambda: world.get('b')
        ]

        def worker():
            import random
            for f in random.choices(actions, k=20):
                f()

        ThreadSafetyTest.run(worker, n_threads=5)
        assert not failures

    with world.test.empty():

        class C(Provider):
            def change_state(self):
                with self._container_lock():
                    pass

        # Should not raise any error if not bound to any container yet
        C().change_state()
Ejemplo n.º 13
0
def test_factory_scope(provider: WorldTestProvider):
    scope = world.scopes.new(name='dummy')
    provider.add_factory(Service, factory=lambda: Service(), scope=scope)

    s = world.get(Service)
    assert world.get(Service) is s

    world.scopes.reset(scope)
    assert world.get(Service) is not s
Ejemplo n.º 14
0
def test_multiple_factories(provider: FactoryProvider, scope: Scope):
    def build2(**kwargs) -> A:
        return A(**kwargs)

    b = provider.register(A, factory=build, scope=scope)
    b2 = provider.register(A, factory=build2, scope=scope)

    assert isinstance(world.get(b), A)
    assert isinstance(world.get(b2), A)
Ejemplo n.º 15
0
def test_singleton():
    class Singleton(Service):
        __antidote__ = Service.Conf(singleton=True)

    assert world.get(Singleton) is world.get(Singleton)

    class NoScope(Service):
        __antidote__ = Service.Conf(singleton=False)

    assert world.get(NoScope) != world.get(NoScope)
Ejemplo n.º 16
0
def test_scope_support():
    dummy_scope = world.scopes.new(name='dummy')

    class X(Service):
        __antidote__ = Service.Conf(scope=dummy_scope)

    with world.test.clone():
        x = world.get(X)
        assert x is world.get(X)
        world.scopes.reset(dummy_scope)
        assert world.get(X) is not x

        @world.test.override.factory(1, scope=dummy_scope)
        def build():
            return object()

        x = world.get(1)
        assert x is world.get(1)
        world.scopes.reset(dummy_scope)
        assert world.get(1) is not x

        @world.test.override.provider()
        def provide(dependency):
            if dependency == 2:
                return DependencyValue(object(), scope=dummy_scope)

        x = world.get(2)
        assert x is world.get(2)
        world.scopes.reset(dummy_scope)
        assert world.get(2) is not x
Ejemplo n.º 17
0
def test_freeze(indirect: IndirectProvider, permanent):
    world.freeze()

    with pytest.raises(FrozenWorldError):
        indirect.register_implementation(Interface, lambda: A, permanent=False)

    with pytest.raises(FrozenWorldError):
        indirect.register_implementation(Interface, lambda: A, permanent=True)

    with pytest.raises(DependencyNotFoundError):
        world.get(Interface)
Ejemplo n.º 18
0
def test_method_same_instance():
    class Test(Service):
        def get(self):
            return self

        A = LazyMethodCall(get, singleton=True)
        B = LazyMethodCall(get, singleton=False)

    instance = world.get(Test)
    assert world.get(Test.A) is instance
    assert world.get(Test.B) is instance
Ejemplo n.º 19
0
def test_no_const():
    class Config(Constants):
        A = 'a'

        def provide_const(self, name, arg):
            return arg * 2

    with pytest.raises(DependencyNotFoundError):
        world.get(Config.A)

    conf = Config()
    assert conf.A == 'a'
Ejemplo n.º 20
0
def test_no_strict_validation(wire, kwargs):
    @wire(**kwargs)
    class A:
        def f(self, x):
            return x

        def g(self, x, y):
            return x, y

    a = A()
    assert a.f() == world.get("x")
    assert a.g() == (world.get("x"), world.get("y"))
Ejemplo n.º 21
0
def test_clone_keep_singletons():
    world.test.singleton("singleton", 2)
    world.provider(DummyIntProvider)

    with world.test.clone(keep_singletons=True):
        assert world.get("singleton") == 2
        assert world.get(10) == 20

    with world.test.clone(keep_singletons=False):
        with pytest.raises(DependencyNotFoundError):
            world.get("singleton")
        assert world.get(10) == 20
Ejemplo n.º 22
0
def test_no_strict_validation_auto_provide(wire):
    @wire(auto_provide=[MyService, AnotherService])
    class A:
        def f(self, x: MyService):
            return x

        def g(self, x: MyService, y: AnotherService):
            return x, y

    a = A()
    assert a.f() == world.get(MyService)
    assert a.g() == (world.get(MyService), world.get(AnotherService))
Ejemplo n.º 23
0
def test_custom_scope(provider: ServiceProvider):
    dummy_scope = world.scopes.new(name='dummy')

    class MyService:
        pass

    provider.register(MyService, scope=dummy_scope)

    my_service = world.get(MyService)
    assert my_service is world.get(MyService)
    world.scopes.reset(dummy_scope)
    assert my_service is not world.get(MyService)
Ejemplo n.º 24
0
def test_register_singleton():
    @service(singleton=True)
    class Singleton:
        pass

    assert world.get(Singleton) is world.get(Singleton)

    @service(singleton=False)
    class NoScope:
        pass

    assert world.get(NoScope) != world.get(NoScope)
Ejemplo n.º 25
0
def test_implementation_debug():
    class Interface:
        pass

    prefix = "tests.world.test_debug.test_implementation_debug.<locals>"

    with world.test.new():

        class Dummy(Interface, Service):
            pass

        @implementation(Interface)
        def f():
            return Dummy

        assert_valid(
            DebugTestCase(value=Interface @ f,
                          expected=f"""
                Permanent implementation: {prefix}.Interface @ {prefix}.f
                └── {prefix}.Dummy
                    """))

        world.get(Interface @ f)
        assert_valid(
            DebugTestCase(value=Interface @ f,
                          expected=f"""
                Permanent implementation: {prefix}.Interface @ {prefix}.f
                └── {prefix}.Dummy
                    """))

    with world.test.new():

        class Dummy2(Interface, Service):
            pass

        undefined_expectations = f"""
            <∅> Implementation: {prefix}.Interface @ {prefix}.g
            └── {prefix}.Dummy2
        """

        @implementation(Interface, permanent=False)
        def g():
            return Dummy2

        assert_valid(
            DebugTestCase(value=Interface @ g,
                          expected=undefined_expectations))

        world.get(Interface @ g)
        assert_valid(
            DebugTestCase(value=Interface @ g,
                          expected=undefined_expectations))
Ejemplo n.º 26
0
def test_factory_scope():
    with world.test.empty():
        scope = world.scopes.new(name='dummy')

        @world.test.factory(Service, scope=scope)
        def build():
            return Service()

        s = world.get(Service)
        assert world.get(Service) is s

        world.scopes.reset(scope)
        assert world.get(Service) is not s
Ejemplo n.º 27
0
def test_dependencies(wire, wired_method_builder):
    f = wired_method_builder(wire(methods=['f'], dependencies=('y',)))
    assert f() is world.get('y')

    f = wired_method_builder(wire(methods=['f'], dependencies=dict(x='z')))
    assert f() is world.get('z')

    f = wired_method_builder(wire(methods=['f'], dependencies=dict(y='z')))
    with pytest.raises(TypeError):
        f()

    f = wired_method_builder(wire(methods=['f'], dependencies=lambda arg: arg.name * 2))
    assert f() is world.get('xx')
Ejemplo n.º 28
0
def test_subclass_classmethod(wire):
    @wire(auto_provide=True)
    class Dummy:
        @classmethod
        def cls_method(cls, x: MyService):
            return cls, x

    assert (Dummy, world.get(MyService)) == Dummy.cls_method()

    class SubDummy(Dummy):
        pass

    assert (SubDummy, world.get(MyService)) == SubDummy.cls_method()
Ejemplo n.º 29
0
def test_name():
    class Config(Constants):
        A = const()
        B = const()

        def provide_const(self, name, arg):
            return name

    assert world.get(Config.A) == 'A'
    assert world.get(Config.B) == 'B'
    conf = Config()
    assert conf.A == 'A'
    assert conf.B == 'B'
Ejemplo n.º 30
0
def test_default_get():
    class Config(Constants):
        NOTHING = const()
        B = const("B")

    with pytest.raises(DependencyInstantiationError):
        world.get(Config.NOTHING)

    with pytest.raises(ValueError, match=".*NOTHING.*"):
        Config().NOTHING

    assert world.get(Config.B) == 'B'
    assert Config().B == "B"