python模拟检查对象的方法是否被访问(未被调用)

2024-04-26 14:37:52 发布

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

class A():
    def tmp(self):
        print("hi")

def b(a):
    a.tmp # note that a.tmp() is not being called. In the project I am working on, a.tmp is being passed as a lambda to a spark executor. And as a.tmp is being invoked in an executor(which is a different process), I can't assert the call of tmp

我想测试是否调用过a.tmp。我该怎么做?请注意,我仍然不想模仿tmp()方法,而是更喜欢python check if a method is called without mocking it away行中的内容


Tags: theselfthatisdefasnothi
1条回答
网友
1楼 · 发布于 2024-04-26 14:37:52

没有经过测试,也许有更好的方法来使用Mock,但无论如何:

def mygetattr(self, name):
    if name == "tmp":
        self._tmp_was_accessed = True
    return super(A, self).__getattribute__(name)

real_getattr = A.__getattribute__
A.__getattribute__ = mygetattr
try:
    a = A()
    a._tmp_was_accessed = False
    b(a)
finally:
    A.__getattribute__  real_getattr
print(a._tmp_was_accessed)

相关问题 更多 >