From 8c3477a000bb95827d59d621a22f8b00f332be1a Mon Sep 17 00:00:00 2001 From: Mike Salvatore Date: Tue, 26 Apr 2022 02:32:02 -0400 Subject: [PATCH] Common: Raise TypeError if DIContainer.register() called with instance --- monkey/common/di_container.py | 7 +++++++ monkey/tests/unit_tests/common/test_di_container.py | 6 ++++++ 2 files changed, 13 insertions(+) diff --git a/monkey/common/di_container.py b/monkey/common/di_container.py index 55ba31923..6086440e7 100644 --- a/monkey/common/di_container.py +++ b/monkey/common/di_container.py @@ -25,6 +25,13 @@ class DIContainer: :param interface: An interface or abstract base class that other classes depend upon :param concrete_type: A type (class) that implements `interface` """ + if not inspect.isclass(concrete_type): + raise TypeError( + "Expected a class, but received an instance of type " + f'"{concrete_type.__class__.__name__}"; Pass a class, not an instance, to ' + "register(), or use register_instance() instead." + ) + self._type_registry[interface] = concrete_type DIContainer._del_key(self._instance_registry, interface) diff --git a/monkey/tests/unit_tests/common/test_di_container.py b/monkey/tests/unit_tests/common/test_di_container.py index 1d1e4ea5c..1caa55ca4 100644 --- a/monkey/tests/unit_tests/common/test_di_container.py +++ b/monkey/tests/unit_tests/common/test_di_container.py @@ -260,3 +260,9 @@ def test_resolve_dependencies(container): assert isinstance(dependencies[0], ServiceA) assert isinstance(dependencies[1], ServiceB) + + +def test_register_instance_as_type(container): + service_a_instance = ServiceA() + with pytest.raises(TypeError): + container.register(IServiceA, service_a_instance)