[英]python mocking check if a method of an object was accessed(not called)
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
I want to test whether a.tmp was ever invoked. 我想测试是否曾经调用过a.tmp。 How do I do that? 我怎么做? Note that I still don't want to mock away the tmp() method and would prefer something on the lines of python check if a method is called without mocking it away 请注意,我仍然不想嘲笑tmp()方法,而是希望在python的代码行中检查是否在不嘲笑的情况下调用了方法
Not tested, and there's probably a much better way with Mock
but anyway: 未经测试,使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.