python mock - 在不妨碍实现的情况下修补方法

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

问题描述

是否有一种干净的方法来修补对象,以便在测试用例中获得 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:要包装的模拟对象的项目.如果 wraps 不是 None 那么调用 Mock 会将调用传递给被包装的对象(返回真实结果).模拟上的属性访问将返回一个 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 mock - 在不妨碍实现的情况下修补方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:为迭代定制 unittest.mock.mock_open 下一篇:Python mock Patch os.environ 和返回值

相关文章

最新文章