python模拟-在不妨碍实现的情况下修补方法 [英] python mock - patching a method without obstructing implementation

查看:80
本文介绍了python模拟-在不妨碍实现的情况下修补方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种干净的方法来修补对象,以使您在测试用例中获得assert_call*助手,而无需实际删除操作?

Is there a clean way to patch an object so that you get the assert_call* helpers in your test case, without actually removing the action?

例如,如何修改@patch行以通过以下测试:

For example, how can I modify the @patch line to get the following test passing:

from unittest import TestCase
from mock import patch


class Potato(object):
    def foo(self, n):
        return self.bar(n)

    def bar(self, n):
        return n + 2


class PotatoTest(TestCase):

    @patch.object(Potato, 'foo')
    def test_something(self, mock):
        spud = Potato()
        forty_two = spud.foo(n=40)
        mock.assert_called_once_with(n=40)
        self.assertEqual(forty_two, 42)

我也许可以使用side_effect一起破解,但是我希望有一种更好的方法可以在所有函数,类方法,静态方法,未绑定方法等上以相同的方式工作.

I could probably hack this together using side_effect, but I was hoping there would be a nicer way which works the same way on all of functions, classmethods, staticmethods, unbound methods, etc.

推荐答案

与您的解决方案类似,但使用wraps:

Similar solution with yours, but using wraps:

def test_something(self):
    spud = Potato()
    with patch.object(Potato, 'foo', wraps=spud.foo) as mock:
        forty_two = spud.foo(n=40)
        mock.assert_called_once_with(n=40)
    self.assertEqual(forty_two, 42)

根据文档:

包装:要包装的模拟对象的项目.如果wraps不为None,则 调用Mock会将调用传递给包装的对象 (返回实际结果).模拟上的属性访问将返回 一个模拟对象,该对象包装被包装的相应属性 对象(因此尝试访问不存在的属性 引发AttributeError).

wraps: Item for the mock object to wrap. If wraps is not None then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn’t exist will raise an AttributeError).


class Potato(object):

    def spam(self, n):
        return self.foo(n=n)

    def foo(self, n):
        return self.bar(n)

    def bar(self, n):
        return n + 2


class PotatoTest(TestCase):

    def test_something(self):
        spud = Potato()
        with patch.object(Potato, 'foo', wraps=spud.foo) as mock:
            forty_two = spud.spam(n=40)
            mock.assert_called_once_with(n=40)
        self.assertEqual(forty_two, 42)

这篇关于python模拟-在不妨碍实现的情况下修补方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆