I'm brand new to unit testing and mock. I would like to have a mock method append to a dictionary, but I'm not sure how I can accomplish this. I need to pass key and value arguments to append_dict
. Using this, I get
SyntaxError: can't assign to function call
Code:
def mock_client(dictionary):
client = mock.MagicMock()
client.dictionary = dictionary
client.append_dictionary(key, value) = client.dictionary[key] = value #this line doesn't work
return client
The function is called in the file I want to test like so:
client.append_dictionary(key, value)
You could write the method directly and set it to the client
object:
def mock_client(dictionary):
client = mock.MagicMock()
client.dictionary = dictionary
def append_dictionary(self, key, value):
self.dictionary[key] = value
client.append_dictionary = append_dictionary
return client
On the other hand, if you wish to test whether append_dictionary
is called properly in your code it may be better to do something like this:
mocked_client = mock_client({})
my_code(mocked_client)
self.assertEqual(
mocked_client.append_dictionary.call_args_list,
[
mock.call("key", "value"),
]
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.