【问题标题】:python mocking check if a method of an object was accessed(not called)python mocking 检查对象的方法是否被访问(未调用)
【发布时间】:2018-06-22 09:20:13
【问题描述】:
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

【问题讨论】:

    标签: python mocking python-unittest magicmock


    【解决方案1】:

    未经测试,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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      相关资源
      最近更新 更多