简体   繁体   English

python unittest - 如何保留已转换为 Mock object 的函数的副作用?

[英]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_countassert_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.

相关问题 python 单元测试:如何模拟对象的构造以返回模拟? - python unittest: How to mock an object's construct to return a mock? 如何在 Python 的请求库中模拟会话中的副作用? - How to mock side effects in session in Python's request library? 如何模拟在python中写入同一对象的对象函数? - How to mock an object's function which writes to the same object in python? 如何使用 Python 的 unittest 测试是否已抛出警告? - How to test with Python's unittest that a warning has been thrown? 在不使用模拟的情况下检查是否已在Python unittest中调用函数的规范方法是什么? - What is the canonical way to check if a function has been called in Python unittest without use of a mock? 使用Python的UnitTest模拟对象创建新对象 - Using Python's UnitTest Mock for a new Object 如何使用unittest.mock从代码中删除副作用? - How can I use unittest.mock to remove side effects from code? 如何检查模拟是否有任何副作用? - How to check if mock has any side effects left? 模拟在单元测试python中使用成员变量的类的私有函数 - Mock a private function of a class which uses member variables in unittest python 当调用python Mock时,如何运行函数(以获得副作用)? - How can I run a function (to get side effects) when a python Mock is called?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM