[英]python unittest - How to preserve a function's side effects which has been converted into a Mock object?
I want to count the number of times that a function is called, python patch has been recommended allowing me to call call_count
and things like assert_not_called
to verify just that.我想计算调用 function 的次数,建议使用 python 补丁允许我调用
call_count
和assert_not_called
之类的东西来验证这一点。
My problem is that I want the function to perform just as it did, as its function is required for the tests and it's on dynamic data so I cannot simply hardcode the result.我的问题是我希望 function 能够像它一样执行,因为它的 function 是测试所必需的,而且它是动态数据的,所以我不能简单地对结果进行硬编码。
with patch.object(shutil, 'copy') as mm:
do_some_things()
mm.assert_not_called()
For do_some_things()
to work correctly, shutil.copy still needs to perform its original role为了
do_some_things()
正常工作,shutil.copy 仍然需要执行其原始角色
I would suggest just using patch
not patch.object
.我建议只使用
patch
而不是patch.object
。 You can still accomplish all you want with that.你仍然可以用它来完成你想要的一切。 I don't having anything in
~/test
我在
~/test
中没有任何内容
from unittest import TestCase
from unittest.mock import patch
from shutil import copy
def do_some_things(src, dst):
copy(src, dst)
class TestDoSomething(TestCase):
def test_do_somethings(self):
with patch('test_do_some_things.copy') as mm:
do_some_things('~/test.txt', '~/test/test.txt')
mm.called_once()
print(mm.call_count)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.