From 45751322b8985d43ad3e61ea93d4370a3da65857 Mon Sep 17 00:00:00 2001 From: Kurt Steinkraus Date: Sun, 7 Jul 2013 20:47:04 -0700 Subject: [PATCH] Validates python type of ObjectGraph.provide() arg. --- TODO | 5 ++--- pinject/object_graph.py | 7 +++++++ pinject/object_graph_test.py | 17 +++++++++++++++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/TODO b/TODO index 7ff7a62..878f67e 100644 --- a/TODO +++ b/TODO @@ -1,8 +1,5 @@ TODO: -- validate python types of all input - allow binding specs to declare required bindings -- standard tests for scopes (reentrant? thread-safe?), annotations (eq? - hash?), etc. - describe features specifically omitted, e.g., - field injection - circular injection @@ -10,6 +7,8 @@ TODO: - figure out whether/how Pinject works with inheritance Maybe TODO: +- standard tests for scopes (reentrant? thread-safe?), annotations (eq? + hash?), etc. - change default scope back to prototype? - eager singletons - allow field injection diff --git a/pinject/object_graph.py b/pinject/object_graph.py index 4f33dfe..90b22f5 100644 --- a/pinject/object_graph.py +++ b/pinject/object_graph.py @@ -148,6 +148,12 @@ def new_object_graph( use_short_stack_traces) +def _verify_type(elt, required_type, arg_name): + if type(elt) != required_type: + raise errors.WrongArgTypeError( + arg_name, required_type.__name__, type(elt).__name__) + + def _verify_types(seq, required_type, arg_name): if not isinstance(seq, collections.Sequence): raise errors.WrongArgTypeError( @@ -199,6 +205,7 @@ def provide(self, cls): Raises: Error: an instance of cls is not providable """ + _verify_type(cls, types.TypeType, 'cls') if not self._is_injectable_fn(cls): provide_loc = locations.get_back_frame_loc() raise errors.NonExplicitlyBoundClassError(provide_loc, cls) diff --git a/pinject/object_graph_test.py b/pinject/object_graph_test.py index b2cf1b7..cbaacba 100644 --- a/pinject/object_graph_test.py +++ b/pinject/object_graph_test.py @@ -145,6 +145,16 @@ def test_raises_exception_if_is_scope_usable_from_scope_is_wrong_type(self): is_scope_usable_from_scope=42) +class VerifyTypeTest(unittest.TestCase): + + def test_verifies_correct_type_ok(self): + object_graph._verify_type(types, types.ModuleType, 'unused') + + def test_raises_exception_if_incorrect_type(self): + self.assertRaises(errors.WrongArgTypeError, object_graph._verify_type, + 'not-a-module', types.ModuleType, 'an-arg-name') + + class VerifyTypesTest(unittest.TestCase): def test_verifies_empty_sequence_ok(self): @@ -540,6 +550,13 @@ def provide_foo(self): self.assertRaises(errors.InjectingNoneDisallowedError, obj_graph.provide, SomeClass) + def test_raises_exception_if_trying_to_provide_nonclass(self): + class SomeClass(object): + pass + obj_graph = object_graph.new_object_graph( + modules=None, classes=[SomeClass]) + self.assertRaises(errors.WrongArgTypeError, obj_graph.provide, 42) + class ObjectGraphWrapTest(unittest.TestCase):