指定“类 Foo 的任何实例"对于模拟 assert_call_once_with()? [英] Specifying "any instance of class Foo" for mock assert_called_once_with()?

查看:38
本文介绍了指定“类 Foo 的任何实例"对于模拟 assert_call_once_with()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

assert_Called_once_with中,如何指定参数是类Foo的任何实例"?

In assert_called_once_with, how can I specify a parameter is "any instance of class Foo"?

例如:

class Foo(): pass
def f(x): pass
def g(): f(Foo())
import __main__
from unittest import mock

mock.ANY 当然通过了:

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

当然,另一个 Foo 实例没有通过.

and of course, another instance of Foo doesn't pass.

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 的任何实例都可以使断言通过?

What can I put as my expected parameter such that any instance of Foo will make the assertion pass?

推荐答案

一个简单的解决方案是分两步完成:

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)


但是,如果您查看 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()

你可以看到它只是一个等于任何东西的对象.所以你可以定义你自己的等价物,它等于 Foo 的任何实例:

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:

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()

或更笼统地说:

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)

无论哪种方式,您都可以像ANY一样使用它:

Either way, you can use it as you would ANY:

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

这篇关于指定“类 Foo 的任何实例"对于模拟 assert_call_once_with()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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