For example I have a function like below:
def func(val):
dict = {}
# some logic to fill in dict
dict['a'] = val
Then how can I pytest the the contents of dict? Is it possible?
For example I have a function like below:
def func(val):
dict = {}
# some logic to fill in dict
dict['a'] = val
Then how can I pytest the the contents of dict? Is it possible?
You can actually replace the dict constructor, for the tested module, if you can change your code slightly. Suppose that your module name is my_module.py and you can make the following changes:
dict() instead of {}dict into my_dict (or any other name so it doesn't shadows the builtin dict())my_module.py would look like so:
def func(val):
my_dict = dict() # instead of dict = {}
# some logic to fill in dict
my_dict['a'] = val
Then, in your test, override the dict constructor which creates new dictionaries and return your dictionary that you can assert later on:
from my_module import func
def test_func(mocker):
my_replaced_dict = {}
mocker.patch("my_module.dict", return_value=my_replaced_dict)
func(20)
assert my_replaced_dict['a'] == 20 # the assert works since func uses our variable