I am new to unit testing in Python. I am trying to unit test a method that does something like this:
MyClass:
client : Client
def __init__(client):
self.client=client
def method_to_test(self):
images = self.client.get_stuff()
image = images[0]
result = []
for region in image.regions:
result.append(region.region_id)
return result
I have tried mocking and nesting of all the classes involved: Client, Image and ImageRegion. But at some point the mocking breaks down and my test fails. Is there a way to mock things so that one can do something like:
def test_method_to_test():
result = MyClass(mock_client).method_to_test()
assert dummy_region_id in result
... or perhaps better ways to test in such situations with nested custom objects?
My latest attempt looks like this:
with patch('package.module.ImageRegion') as MockRegion:
region = MockRegion()
region.region_id.return_value = dummy_region_id
with patch('package.module.Image') as MockImage:
image = MockImage()
image.regions.return_value = [region]
with patch('package.module.Client') as MockClient:
mock_client = MockClient()
mock_client.get_regions.return_value = [image]
result = MyClass(mock_client).method_to_test()
assert dummy_region_id in result