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 检查某些内容,如果调用方法而不嘲笑它

未经测试,可能有更好的方法处理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)

相关内容

  • 没有找到相关文章

最新更新