Skip to content
Advertisement

Mock and patch class method and give its return value to another function

Here are my snippets

module1.py
class Client:

def __init__(self):
    self.api_client = APIClient()

def get_resources(self):
    #this method gets some data
    #end returns list with dictionaries
    return [{k1:v1},{k2:v2} ...]

 module2
 config = {}
 
 def add_config(resource):
     #process the data pass by resource
     config[resource[k1]] = data

 def instantiate_config():
     for item in Client().get_resources()
         add_config(item)

So I want to test this instantiate_config with pytest. Here is my try:

@patch('module1.Client.get_resources')
def test_instantiate_config(self, client_mock):

    dummy_data = {some_dummy_data}
    #it is a copy of the list, returned form Client().get_resources()

    client_mock.get_resources.returned_values = dummy_data
    instantiate_config()

    assert 'key1' in config #config is the same config from module2

But this gives empty config dict. I don’t know is that possible – to mock Client().get_resources() to give it same value and that value to be passed automatically as argument to add_config_func. If it it not what is the best way to test instantiate_config function. Not sure is in clear or not, cuz it is a little bit long story

Advertisement

Answer

Your mock is already representing the method get_resources, and you have a typo in “returned_values”. Change to : client_mock.return_value = dummy_data

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement