簡體   English   中英

python模擬檢查是否訪問了對象的方法(未調用)

[英]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

我想測試是否曾經調用過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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM