Exemple #1
0
    def test__alias(self):
        test_instance_type = mock.Mock()
        container = DIContainer({
            'test_instance': {
                'type': test_instance_type,
                'args': {
                    '': ["arg1", ],
                    'arg2': 'arg2',
                    'arg3': 'rel:inject_rel'
                },
                'properties': {
                    'prop1': 'prop1',
                    'prop2': 'prop2',
                    'prop3': 'rel:inject_alias'
                },
                'alias': ['alias_name']
            },
            'inject_rel': {
                'type': mock.Mock(),
                'singleton': True,
                'properties': {
                    'name': 'inject_rel'
                },
                'alias': ['inject_alias']
            }
        })

        instance = container.resolve("alias_name")
        inject_rel = container.resolve("inject_rel")
        test_instance_type.assert_called_with("arg1", arg2="arg2", arg3=inject_rel)
        self.assertEqual(instance.prop1, 'prop1')
        self.assertEqual(instance.prop2, 'prop2')
        self.assertEqual(instance.prop3, inject_rel)
Exemple #2
0
    def test__parent_lookup(self):
        """
        Passes if ...
        """
        container = DIContainer({
            'one': {
                'type': 'mock.Mock',
                'properties': {
                    'from': 'parent'
                }
            }
        })

        context_settings = {
            'two': {
                'type': 'mock.Mock',
                'properties': {
                    'from': 'child'
                }
            }
        }

        with container.context(context_settings):
            self.assertIsNotNone(container.resolve("one"))
            self.assertIsNotNone(container.resolve_type("one"))

        self.assertRaises(MissingConfigurationError, lambda: container.resolve("three"))
        self.assertRaises(MissingConfigurationError, lambda: container.resolve_type("three"))
Exemple #3
0
    def test__copy_config(self):
        """
        Passes if the settings variable becomes copies and changes do not
        take effect.
        :return:
        """

        conf = {
            'a': {
                'type': 'mock.Mock'
            }
        }

        container = DIContainer(conf)

        self.assertIn('a', container.settings)
        self.assertNotIn('b', container.settings)
        self.assertRaises(KeyError, lambda: container.resolve('b'))

        conf['b'] = {
            'type': 'mock.MagicMock'
        }

        self.assertIn('a', container.settings)
        self.assertNotIn('b', container.settings)

        self.assertIsNotNone(container.resolve('a'))
        self.assertRaises(KeyError, lambda: container.resolve('b'))
Exemple #4
0
    def test__non_singleton(self):
        """
        Passes if the singleton configuration works and different instances
        are given if resolve is called twice.
        """
        container = DIContainer({
            'non_singleton': DIConfig(type='mock.MagicMock', singleton=False)
        })

        first = container.resolve('non_singleton')
        second = container.resolve('non_singleton')

        self.assertNotEqual(first, second)
        self.assertNotIn('non_singleton', container.singletons)
Exemple #5
0
    def test__singleton(self):
        """
        Passes if the singleton configuration works and the same instance
        if given if resolve is called twice.
        """
        container = DIContainer({
            'singleton': DIConfig(type='mock.MagicMock', singleton=True)
        })

        first = container.resolve('singleton')
        second = container.resolve('singleton')

        self.assertEqual(first, second)
        self.assertIn('singleton', container.singletons)
Exemple #6
0
        def inner_test(setting):

            container = DIContainer({
                'main_instance': DIConfig(
                    type='mock.MagicMock',
                    args={'referenced_instance_construct': setting},
                    properties={'referenced_instance_property': setting}),
                'referenced_instance': DIConfig(type='mock.MagicMock', singleton=True)
            })

            main = container.resolve('main_instance')
            referenced = container.resolve('referenced_instance')
            self.assertEqual(main.referenced_instance_construct, referenced)
            self.assertEqual(main.referenced_instance_property, referenced)
Exemple #7
0
    def test__constructor_args(self):
        """
        Passes if the registered type becomes constructed with the
        overriding args and kwargs.
        """
        mock_type = mock.Mock()
        container = DIContainer({
            'instance': {
                'type': mock_type,
                'args': {'arg1': 1, 'arg2': 'two'}
            }
        })
        instance = container.resolve("instance")
        mock_type.assert_called_with(arg1=1, arg2='two')

        mock_type.reset_mock()

        instance = container.resolve("instance", arg1='one', arg2=2)
        mock_type.assert_called_with(arg1='one', arg2=2)
Exemple #8
0
        def inner_test(setting):
            container = DIContainer({
                'main_instance': DIConfig(
                    type='mock.MagicMock',
                    args={'python_version_construct': setting},
                    properties={'python_version_property': setting})
            })

            main = container.resolve('main_instance')
            self.assertEqual(main.python_version_construct, sys.version)
            self.assertEqual(main.python_version_property, sys.version)
Exemple #9
0
        def inner_test(setting):
            container = DIContainer({
                'test_instance': DIConfig(
                    type='mock.MagicMock',
                    args={'serializer_constructor': setting},
                    properties={'serializer_property': setting})
            })

            instance = container.resolve('test_instance')
            self.assertEqual(instance.serializer_constructor, json)
            self.assertEqual(instance.serializer_property, json)
Exemple #10
0
        def inner_test(setting):
            container = DIContainer({
                'instance': DIConfig(
                    type='mock.MagicMock',
                    args={'attr_value_constructor': setting},
                    properties={'attr_value_property': setting})
            })

            instance = container.resolve('instance')
            self.assertEqual(instance.attr_value_constructor, ATTR_VALUE)
            self.assertEqual(instance.attr_value_property, ATTR_VALUE)
Exemple #11
0
    def test__register_replace(self):
        """
        Passes if the configuration of `to_be_replaced` becomes replaced.
        """
        container = DIContainer({
            'to_be_replaced': {
                'type': 'mock.Mock',
                'properties': {
                    'id': '123456789'
                }
            }
        })

        inst = container.resolve("to_be_replaced")
        self.assertEqual(inst.id, '123456789')

        repl_config = {'type': 'mock.Mock', 'properties': {'id': '987654321'}}
        container.register("to_be_replaced", repl_config, True)

        inst = container.resolve("to_be_replaced")
        self.assertEqual(inst.id, '987654321')
Exemple #12
0
    def test__hooks_called(self):

        # TODO: improve.

        container = DIContainer({'a': DIConfig(
            type='mock.Mock',
            args={'': [mock.Mock()], 'b': mock.Mock()}
        )}, event_dispatcher=mock.Mock())

        container.resolve('a')
        container.clear()
        container.resolve_type('a')
        container.register('b', DIConfig(type='mock.Mock'))

        for method in ('initialized', 'before_register', 'after_register',
                       'after_resolve', 'before_resolve', 'before_build_up',
                       'after_build_up', 'before_resolve_type', 'after_resolve_type',
                       'after_clear',):
            self.assertTrue(
                getattr(container.event_dispatcher, method).called,
                'method {0} not called.'.format(method))
Exemple #13
0
    def test_events(self):
        manager = DIContainer(TEST_DI_SETTINGS, event_dispatcher=mock.MagicMock)
        for name in ('jens',):
            manager.resolve(name)

        manager.resolve_type('jessica')
        manager.clear()
        manager.register('henrik_2', {
            'type': 'test.TestPerson',
            'singleton': True,
            'args': {'': ['Henrik', 'Blawatt', 24]}
        })

        for method in ('initialized', 'before_register', 'after_register',
                       'after_resolve', 'before_resolve', 'before_build_up',
                       'after_build_up', 'before_resolve_type', 'after_resolve_type',
                       'after_clear',):
            self.assertTrue(
                getattr(manager.event_dispatcher, method).called,
                'called method {0}.'.format(method)
            )
Exemple #14
0
    def test_resolver_attr(self):

        container = DIContainer({})
        container.register('python_sys', {
            'type': 'mock.MagicMock',
            'args': {
                'version_info': attr('sys.version_info')
            }
        })

        py_sys = container.resolve('python_sys')
        self.assertEqual(py_sys.version_info, sys.version_info)
Exemple #15
0
    def test__assert_init_args(self):

        mock_types = mock.Mock()
        mock_types.ArgsCalledType = mock.Mock(name='ArgsCalledType')
        mock_types.KWargsCalledType = mock.Mock(name='KWargsCalledType')
        mock_types.MixedCalledType = mock.Mock(name='MixedCalledType')

        sys.modules['mock_types'] = mock_types

        args = [mock.Mock(), mock.Mock()]
        kwargs = {'a': mock.Mock(), 'b': mock.Mock()}
        mixed = {'': args}
        mixed.update(kwargs)

        container = DIContainer({
            'args_instance': DIConfig(type='mock_types.ArgsCalledType', args=args),
            'kwargs_instance': DIConfig(type='mock_types.KWargsCalledType', args=kwargs),
            'mixed_instance': DIConfig(type='mock_types.MixedCalledType', args=mixed)
        })

        container.resolve('args_instance')
        self.assertEqual(mock_types.ArgsCalledType.called, 1)
        mock_types.ArgsCalledType.assert_called_with(*args)

        container.resolve('kwargs_instance')
        self.assertEqual(mock_types.KWargsCalledType.called, 1)
        mock_types.KWargsCalledType.assert_called_with(**kwargs)

        container.resolve('mixed_instance')
        self.assertEqual(mock_types.MixedCalledType.called, 1)
        mock_types.MixedCalledType.assert_called_with(*args, **kwargs)
Exemple #16
0
    def test__register_decorator(self):
        """
        Passes if `MyService` becomes registered with the given settings.
        """
        container = DIContainer({})

        @container.register("my_service", settings=dict(properties={'foo': 'bar'}))
        class MyService(object):
            pass

        result = container.resolve("my_service")
        self.assertIsNotNone(result)
        self.assertEqual(result.foo, "bar")
Exemple #17
0
    def test__register_without_settings(self):
        """
        Passes if `MyService` becomes registered without providing settings.
        """
        container = DIContainer({})

        @container.register("my_service")
        class MyService(object):
            pass

        result = container.resolve("my_service")
        self.assertIsNotNone(result)
        self.assertIsInstance(result, MyService)
Exemple #18
0
    def test__extend_path(self):
        tmp_file = tempfile.NamedTemporaryFile(mode='w+b', suffix='.py', delete=False)
        tmp_file.write(bytes(b'# coding: utf-8\nclass DynamicDummy(object):\n  pass'))
        tmp_file.close()
        basename = os.path.basename(tmp_file.name)
        filename, ext = os.path.splitext(basename)
        container = DIContainer({
            'dynamic': DIConfig(type='{0}:{1}.DynamicDummy'.format(tempfile.tempdir, filename))
        })
        instance = container.resolve('dynamic')
        self.assertIsNotNone(instance)
        module_ = sys.modules[filename]
        self.assertIsInstance(instance, module_.DynamicDummy)

        os.remove(tmp_file.name)
Exemple #19
0
 def test__del_singleton_on_register(self):
     """
     Passes of the singletons instance becomes deleted on reregistering
     the name and replace it.
     """
     type_conf = {
         "type": "mock.Mock",
         "singleton": True
     }
     container = DIContainer({
         "test": type_conf
     })
     t = container.resolve("test")
     self.assertTrue("test" in container.singletons)
     container.register("test", type_conf, replace=True)
     self.assertFalse("test" in container.singletons)
Exemple #20
0
    def test__inject(self):
        """
        Passes if the instance with the key `service` becomes injected into
        a dummy function.
        """
        container = DIContainer({'service': DIConfig(type=mock.Mock, singleton=True)})

        @container.inject(service='service')
        def some_function(data, service):
            service.call_service_function(data)

        some_function('data')
        some_function(data='data', service=mock.Mock())
        some_function('data', mock.Mock())

        service = container.resolve('service')
        self.assertEqual(service.call_service_function.called, 1)
Exemple #21
0
    def test__simple_resolve(self):
        """
        Passes if john is created with the given arguments and property settings.
        john must be resolvable by `resolve` method and by the containers
        __getitem__ method.
        """
        john_config = self.get_john_doe_config()
        container = DIContainer({'john_doe': john_config})
        john_resolve = container.resolve('john_doe')
        john_getitem = container.john_doe
        self.assertIsNotNone(john_resolve)
        self.assertIsNotNone(john_getitem)

        for john in (john_getitem, john_resolve):
            for key, value in john_config['args'].items():
                self.assertEqual(getattr(john, key), value)
            for key, value in john_config['properties'].items():
                self.assertEqual(getattr(john, key), value)
Exemple #22
0
    def test__assert_type(self):
        """
        Passes if the type resolution of `type_implemenation` works and
        the resolution of `no_type_implementation` raises a `ValueError`.
        :return:
        """

        container = DIContainer({
            'type_implementation': DIConfig(type='mock.MagicMock', assert_type='mock.MagicMock'),
            'no_type_implementation': DIConfig(type='object', assert_type='mock.MagicMock')
        })

        resolved_instance = container.resolve('type_implementation')
        self.assertIsNotNone(resolved_instance)

        def raises():
            container.resolve('no_type_implementation')
        self.assertRaises(TypeError, raises)
Exemple #23
0
    def test__register(self):
        """
        Passes if `runtime_config` is not configured and is configured at the
        end of the test. the second registration raises an error.
        """
        container = DIContainer({})

        def raises_not_registred():
            container.resolve('runtime_config')

        self.assertRaises(KeyError, raises_not_registred)
        container.register('runtime_config', {'type': 'mock.MagicMock'})
        runtime_config = container.resolve('runtime_config')
        self.assertIsNotNone(runtime_config)

        def raises_already_registred():
            container.register('runtime_config', {'type': 'mock.MagicMock'})

        self.assertRaises(KeyError, raises_already_registred)
Exemple #24
0
    def test__mixin(self):
        """
        Passes if the created instance is type of the basetype and the given mixins.
        """

        base_type = type(str("BaseType"), (object,), {})
        mixin_type = type(str("MixinType"), (object,), {})

        other_type = type(str("OtherType"), (object,), {})

        container = DIContainer({'a': {
            'type': base_type,
            'mixins': (mixin_type, 'mock.Mock')
        }})

        a = container.resolve("a")

        self.assertIsInstance(a, base_type)
        self.assertIsInstance(a, mixin_type)
        self.assertIsInstance(a, mock.Mock)
        self.assertNotIsInstance(a, other_type)
Exemple #25
0
    def test__factory_method(self):
        """
        Passes if the `TestClass` becomes created using the
        classmethod `create`.
        """
        class TestClass:

            @classmethod
            def create(cls):
                return cls()

        container = DIContainer({'klass': {
            'type': TestClass,
            'factory_method': 'create'
        }})

        with mock.patch.object(TestClass, 'create') as mocked_fn:
            mocked_fn.return_value = TestClass()
            instance = container.resolve('klass')
            self.assertIsNotNone(instance)
            self.assertIsInstance(instance, TestClass)
            self.assertTrue(mocked_fn.called)
Exemple #26
0
class DIContainerTestCase(unittest.TestCase):

    def setUp(self):
        self.manager = DIContainer(TEST_DI_SETTINGS)

    def test__person(self):
        p1 = self.manager.resolve('person')
        p2 = self.manager.resolve('person')

        self.assertIsNotNone(p1)
        self.assertIsNotNone(p2)

        self.assertNotEqual(p1, p2)

    def test__singleton(self):
        j1 = self.manager.resolve('jessica')
        j2 = self.manager.resolve('jessica')

        self.assertIsNotNone(j1)
        self.assertIsNotNone(j2)

        self.assertEqual(j1, j2)

    def test__relation(self):
        jessica = self.manager.resolve('jessica')
        jens = self.manager.resolve('jens')

        self.assertIsNotNone(jessica)
        self.assertIsNotNone(jens)

        self.assertEqual(jens.loves, jessica)
        self.assertEqual(jens.hobbies, ['Tennis', 'Programming'])

    def test__attr(self):
        jens1 = self.manager.resolve('jens')
        jens2 = self.manager.jens

        self.assertEqual(jens1, jens2)

        p1 = self.manager.person
        p2 = self.manager.person

        self.assertNotEqual(p1, p2)

    def test__lazy(self):
        self.assertIn('jens_nl', self.manager.singletons)
        self.assertNotIn('jens', self.manager.singletons)

    def test__register(self):
        self.manager.register('henrik', {
            'type': 'test.TestPerson',
            'singleton': True,
            'args': {'': ['Henrik', 'Blawatt', 24]}
        })

        henrik1 = self.manager.henrik
        henrik2 = self.manager.resolve('henrik')

        self.assertEqual(henrik1, henrik2)
        self.assertEqual(henrik1.first_name, 'Henrik')
        self.assertEqual(henrik1.last_name, 'Blawatt')
        self.assertEqual(henrik1.age, 24)

    def test_autopath(self):

        def create_tempmodule():
            with open(temp_file, 'w') as f:
                f.write(
                    "class AutoPathPerson(object):\n"
                    "    pass\n"
                )

        create_tempmodule()

        jens_autopath = self.manager.jens_autopath
        self.assertIsNotNone(jens_autopath)
        self.assertEqual(jens_autopath.first_name, 'Jens')
        self.assertEqual(jens_autopath.last_name, 'Blawatt')
        self.assertIn(temp_path, sys.path)

    def test_assertbasetype(self):

        def will_raise():
            o = self.manager.jens_assert_no_base
            assert o

        def will_not_raise():
            o = self.manager.jens_assert_base
            assert o

        self.assertRaises(TypeError, will_raise)

        try:
            will_not_raise()
        except Exception as e:
            self.fail('raised unexpected error: %s' % e)

    def test_logging_mod(self):
        objekt = self.manager.logging_mod
        self.assertTrue(isinstance(objekt, dict))
        module = objekt.get('logging')
        self.assertEqual(module.DEBUG, 10)

    def test_logging_ref(self):
        objekt = self.manager.logging_ref
        value = objekt.get('DEBUG')
        self.assertTrue(value, 10)

    def test_resolve_type(self):
        type_ = self.manager.resolve_type('jens')
        self.assertEqual(type_, TestPerson)

    def test_does_not_exist(self):
        def fnc():
            self.manager.does_not_exist
        self.assertRaises(AttributeError, fnc)

    def test_dir(self):
        values = dir(self.manager)
        for k in TEST_DI_SETTINGS.keys():
            self.assertIn(k, values)

    def test_register_registered(self):
        def fnc():
            self.manager.register('jens', dict(type='mock.Mock'))
        self.assertRaises(KeyError, fnc)

    def test_clear_singleton(self):
        def setUp():
            self.manager.singletons['foo'] = 'FOO'
            self.manager.singletons['bar'] = 'BAR'

        setUp()
        self.manager.clear('not-in-singletons')
        self.manager.clear('foo')
        self.assertNotIn('foo', self.manager.singletons)
        self.assertIn('bar', self.manager.singletons)

        self.manager.singletons = dict()

        setUp()
        self.manager.clear()
        self.assertNotIn('foo', self.manager.singletons)
        self.assertNotIn('bar', self.manager.singletons)

    def test_events(self):
        manager = DIContainer(TEST_DI_SETTINGS, event_dispatcher=mock.MagicMock)
        for name in ('jens',):
            manager.resolve(name)

        manager.resolve_type('jessica')
        manager.clear()
        manager.register('henrik_2', {
            'type': 'test.TestPerson',
            'singleton': True,
            'args': {'': ['Henrik', 'Blawatt', 24]}
        })

        for method in ('initialized', 'before_register', 'after_register',
                       'after_resolve', 'before_resolve', 'before_build_up',
                       'after_build_up', 'before_resolve_type', 'after_resolve_type',
                       'after_clear',):
            self.assertTrue(
                getattr(manager.event_dispatcher, method).called,
                'called method {0}.'.format(method)
            )

    def test_inject(self):
        @self.manager.inject(person='jens')
        def to_inject_function(person=None):
            self.assertIsNotNone(person)
            self.assertEqual(person.first_name, 'Jens')

        to_inject_function()

    def test_inject_force(self):
        @self.manager.inject(force=True, person='jens')
        def to_inject_function(person=None):
            self.assertIsNotNone(person)
            self.assertEqual(person.first_name, 'Jens')

        to_inject_function(person=self.manager.jens)

    def test_inject_noforce(self):
        @self.manager.inject(force=False, person='jens')
        def to_inject_function(person=None):
            self.assertIsNotNone(person)
            self.assertEqual(person.first_name, 'Jens')

        to_inject_function(person=self.manager.jens)

    def test_child_container(self):

        ccontainer = self.manager.create_child_container({
            'jens': {
                'type': 'test.TestPerson',
                'args': {
                    'first_name': 'Jens',
                    'last_name': 'Backhaus',
                    'age': 32
                }
            }
        })

        jens_bl = self.manager.resolve('jens')
        jens_ba = ccontainer.resolve('jens')

        self.assertNotEqual(jens_ba, jens_bl)
        self.assertEqual(jens_ba.first_name, jens_bl.first_name)
        self.assertEqual(jens_ba.last_name, 'Backhaus')

    def test_resolver_attr(self):

        container = DIContainer({})
        container.register('python_sys', {
            'type': 'mock.MagicMock',
            'args': {
                'version_info': attr('sys.version_info')
            }
        })

        py_sys = container.resolve('python_sys')
        self.assertEqual(py_sys.version_info, sys.version_info)