如何在python中进行参数匹配、捕获

2024-10-01 17:33:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试理解如何在python外部依赖项中进行mock方法参数匹配和参数捕获。在

1)参数匹配:

class ExternalDep(object):
    def do_heavy_calc(self, anInput):
        return 3

class Client(object):
    def __init__(self, aDep):
        self._dep = aDep

    def invokeMe(self, aStrVal):
        sum = self._dep.do_heavy_calc(aStrVal)
        aNewStrVal = 'new_' + aStrVal
        sum += self._dep.do_heavy_calc(aNewStrVal)

class ClientTest(unittest.TestCase):
    self.mockDep = MagicMock(name='mockExternalDep', spec_set=ExternalDep)
    ###
    self.mockDep.do_heavy_calc.return_value = 5 
    ### this will be called twice regardless of what parameters are used
    ### in mockito-python, it is possible to create two diff mocks (by param),like
    ###
    ### when(self.mockDep).do_heavy_calc('A').thenReturn(7)
    ### when(self.mockDep).do_heavy_calc('new_A').thenReturn(11)
    ###
    ### QUESTION: how could I archive the same result in MagicMock?

    def setUp(self):
        self.cut = Client(self.mockDep)

    def test_invokeMe(self):
        capturedResult = self.cut.invokeMe('A')
        self.assertEqual(capturedResult, 10, 'Unexpected sum')
        # self.assertEqual(capturedResult, 18, 'Two Stubs did not execute')

2)参数捕捉 我在MagicMock或mockito python上都找不到好的文档或示例,无法适应以下模拟场景:

^{pr2}$

如果有人能告诉我如何完成这两个模拟场景(使用MagicMock),我将非常感激!(如有不清楚之处,请询问。)


Tags: self参数defcalcdoclasssumdep
1条回答
网友
1楼 · 发布于 2024-10-01 17:33:57

可能会对您有所帮助的是将assert_called_with与匹配器一起使用。 这将允许您更精细地访问调用中的参数。i、 电子邮箱:

>>> def compare(self, other):
...     if not type(self) == type(other):
...         return False
...     if self.a != other.a:
...         return False
...     if self.b != other.b:
...         return False
...     return True

>>> class Matcher(object):
        def __init__(self, compare, some_obj):
            self.compare = compare
            self.some_obj = some_obj
        def __eq__(self, other):
            return self.compare(self.some_obj, other)

>>> match_foo = Matcher(compare, Foo(1, 2))
>>> mock.assert_called_with(match_foo)

相关问题 更多 >

    热门问题