我希望能够模拟改变参数的函数,并且它的Mutations 是相关的,以便代码继续正确执行.
请考虑以下代码:
def mutate_my_dict(mutable_dict):
if os.path.exists("a.txt"):
mutable_dict["new_key"] = "new_value"
return True
def function_under_test():
my_dict = {"key": "value"}
if mutate_my_dict(my_dict):
return my_dict["new_key"]
return "No Key"
def test_function_under_test():
with patch("stack_over_flow.mutate_my_dict") as mutate_my_dict_mock:
mutate_my_dict_mock.return_value = True
result = function_under_test()
assert result == "new_value"
**请理解,在这种情况下,我知道我可以模拟os.path.存在,但这只是一个例子.我故意想模拟函数,而不是外部模块. **
我还阅读了这里的文档: https://docs.python.org/3/library/unittest.mock-examples.html#coping-with-mutable-arguments个 但它似乎不适合我的箱子.
这是我到目前为止编写的测试,但它显然不起作用,因为密钥发生了变化:
def test_function_under_test():
with patch("stack_over_flow.mutate_my_dict") as mutate_my_dict_mock:
mutate_my_dict_mock.return_value = True
result = function_under_test()
assert result == "new_value"
提前感谢您的宝贵时间:)