[英]Specifying "any instance of class Foo" for mock assert_called_once_with()?
In assert_called_once_with
, how can I specify a parameter is "any instance of class Foo"?在
assert_called_once_with
,如何指定参数是“类 Foo 的任何实例”?
For example:例如:
class Foo(): pass
def f(x): pass
def g(): f(Foo())
import __main__
from unittest import mock
mock.ANY
of course passes: mock.ANY
当然通过:
with mock.patch.object(__main__, 'f') as mock_f:
g()
mock_f.assert_called_once_with(mock.ANY)
and of course, another instance of Foo doesn't pass.当然,另一个 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>)
What can I put as my expected parameter such that any instance of Foo will make the assertion pass?我可以将什么作为我的预期参数,以便 Foo 的任何实例都会使断言通过?
One simple solution is to do this in two steps:一个简单的解决方案是分两步完成:
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)
However, if you look at the implementation of ANY
:但是,如果您查看
ANY
的实现:
class _ANY(object):
"A helper object that compares equal to everything."
def __eq__(self, other):
return True
def __ne__(self, other):
return False
def __repr__(self):
return '<ANY>'
ANY = _ANY()
you can see it's just an object that's equal to anything.你可以看到它只是一个等于任何东西的对象。 So you could define your own equivalent that's equal to any instance of
Foo
:所以你可以定义你自己的等价物,它等于
Foo
任何实例:
class AnyFoo:
"A helper object that compares equal to every instance of Foo."
def __eq__(self, other):
return isinstance(other, Foo)
def __ne__(self, other):
return not isinstance(other, Foo)
def __repr__(self):
return '<ANY Foo>'
ANY_FOO = AnyFoo()
Or more generically:或更笼统地说:
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)
Either way, you can use it as you would ANY
:无论哪种方式,您都可以像
ANY
一样使用它:
with mock.patch.object(__main__, 'f') as mock_f:
g()
mock_f.assert_called_once_with(ANY_FOO)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.