Python 使用()为调用的模拟断言指定“类Foo的任何实例”?

Python 使用()为调用的模拟断言指定“类Foo的任何实例”?,python,mocking,Python,Mocking,在名为_once _with的assert_中,如何将参数指定为类Foo的任何实例 例如: class Foo(): pass def f(x): pass def g(): f(Foo()) import __main__ from unittest import mock 模拟。任何课程通过: with mock.patch.object(__main__, 'f') as mock_f: g() mock_f.assert_called_once_with(mock.ANY)

在名为_once _with的assert_中,如何将参数指定为类Foo的任何实例

例如:

class Foo(): pass
def f(x): pass
def g(): f(Foo())
import __main__
from unittest import mock
模拟。任何课程通过:

with mock.patch.object(__main__, 'f') as mock_f:
  g()
  mock_f.assert_called_once_with(mock.ANY)
当然,Foo的另一个实例没有通过

with mock.patch.object(__main__, 'f') as mock_f:
  g()
  mock_f.assert_called_once_with(Foo())

AssertionError: Expected call: f(<__main__.Foo object at 0x7fd38411d0b8>)
                  Actual call: f(<__main__.Foo object at 0x7fd384111f98>)

我可以将什么作为预期参数,以使任何Foo实例都能使断言通过?

一个简单的解决方案是分两步进行:

with mock.patch.object(__main__, 'f') as mock_f:
    g()
    mock_f.assert_called_once()
    self.assertIsInstance(mock_f.mock_calls[0].args[0], Foo)
但是,如果您查看:

或者更一般地说:

class AnyInstanceOf:
    "A helper object that compares equal to every instance of the specified class."

    def __init__(self, cls):
        self.cls = cls

    def __eq__(self, other):
        return isinstance(other, self.cls)

    def __ne__(self, other):
        return not isinstance(other, self.cls)

    def __repr__(self):
        return f"<ANY {self.cls.__name__}>"


ANY_FOO = AnyInstanceOf(Foo)

一个简单的解决方案是分两步进行:

with mock.patch.object(__main__, 'f') as mock_f:
    g()
    mock_f.assert_called_once()
    self.assertIsInstance(mock_f.mock_calls[0].args[0], Foo)
但是,如果您查看:

或者更一般地说:

class AnyInstanceOf:
    "A helper object that compares equal to every instance of the specified class."

    def __init__(self, cls):
        self.cls = cls

    def __eq__(self, other):
        return isinstance(other, self.cls)

    def __ne__(self, other):
        return not isinstance(other, self.cls)

    def __repr__(self):
        return f"<ANY {self.cls.__name__}>"


ANY_FOO = AnyInstanceOf(Foo)

为什么不断言_调用_一次,然后断言接收到的值呢?我想这就是我要做的。很高兴你把它添加到你的答案中,这两个解决方案都很有用。我非常喜欢mock_f.assert_调用once__,并使用anyinstanceffoo,但是YMMV!我要试试看!为什么不断言_调用_一次,然后断言接收到的值呢?我想这就是我要做的。很高兴你把它添加到你的答案中,这两个解决方案都很有用。我非常喜欢mock_f.assert_调用once__,并使用anyinstanceffoo,但是YMMV!我要试试看!
with mock.patch.object(__main__, 'f') as mock_f:
    g()
    mock_f.assert_called_once_with(ANY_FOO)