Add tests for providers.ExternalDependency & refactoring

This commit is contained in:
Roman Mogilatov 2015-03-16 01:10:43 +02:00
parent 5ef157d252
commit d36e01bf3e
2 changed files with 22 additions and 10 deletions

View File

@ -184,31 +184,26 @@ class ExternalDependency(Provider):
def __init__(self, instance_of):
"""Initializer."""
if not isinstance(instance_of, Iterable):
instance_of = (instance_of,)
self.instance_of = instance_of
self.dependency = None
super(ExternalDependency, self).__init__()
def satisfy(self, provider):
"""Satisfy an external dependency."""
self.dependency = provider
self.dependency = ensure_is_provider(provider)
def __call__(self, *args, **kwargs):
"""Return provided instance."""
if not self.dependency:
raise Error('Dependency is not satisfied')
result = self.dependency.__call__(*args, **kwargs)
instance = self.dependency.__call__(*args, **kwargs)
is_instance = any((isinstance(result, possible_type)
for possible_type in self.instance_of))
if not is_instance:
raise Error('{} is not an '.format(result) +
if not isinstance(instance, self.instance_of):
raise Error('{} is not an '.format(instance) +
'instance of {}'.format(self.instance_of))
return result
return instance
class _StaticProvider(Provider):

View File

@ -376,6 +376,23 @@ class ExternalDependencyTests(unittest.TestCase):
"""ExternalDependency test cases."""
def test_call_satisfied(self):
"""Test call of satisfied external dependency."""
provider = ExternalDependency(instance_of=object)
provider.satisfy(NewInstance(object))
self.assertIsInstance(provider(), object)
def test_call_satisfied_but_not_instance_of(self):
"""Test call of satisfied external dependency, but not instance of."""
provider = ExternalDependency(instance_of=list)
provider.satisfy(NewInstance(dict))
self.assertRaises(Error, provider)
def test_call_not_satisfied(self):
"""Test call of not satisfied external dependency."""
provider = ExternalDependency(instance_of=object)
self.assertRaises(Error, provider)
class StaticProvidersTests(unittest.TestCase):