Reputation: 35
I am new to unit testing. can anyone guide me to test this decorator with mock and patch
def fetch_entity_from_ES(self,func):
@wraps(func)
def ES_wrapper(*args):
entity_type = args[0]
entity_id = args[1]
search_service_utility = ElasticSearchUtilities(self.config)
entity = search_service_utility.fetch_entity_from_ES(entity_type, entity_id)
if not entity:
return func(*args)
return entity
return ES_wrapper
Upvotes: 1
Views: 94
Reputation: 1380
You can test decorators by applying them to a test function. You then run the decorated function and check the behavior.
In this case, the decorated function is an inner function, so it has access to the test method's self etc, if needed.
class TestFetchEntityFromES(TestCase):
def test_fetch_entity_from_ES(self):
@fetch_entity_from_ES
def foo(entity_type, entity_id):
return 'bar'
with patch.object(ElasticSearchUtilities, 'fetch_entity_from_ES',
return_value=None):
self.assertEqual(foo('type1', 'id1'), 'bar')
with patch.object(ElasticSearchUtilities, 'fetch_entity_from_ES',
return_value='baz'):
self.assertEqual(foo('type1', 'id1'), 'baz')
BTW, fetch_entity_from_ES looks like a method because it has a self parameter, but I've treated it as a function.
Upvotes: 1