[英]How do I tell whether a function has been called in Python?
I'm writing unit tests for the first time and am having trouble wrapping my head around this. 我是第一次编写单元测试,但在解决这个问题时遇到了麻烦。 I have a method IsInitialized() that should return false if another method, LoadTable(), has never been called for the object.
我有一个方法IsInitialized(),如果从未为该对象调用另一个方法LoadTable(),则应返回false。 How do I Write a test method to verify this?
如何编写测试方法来验证这一点?
I would make it an attribute for simplicity: 为了简单起见,我将其设为属性:
class with_called_attribute:
def __init__(self, func):
self.func = func
self.called = False
def __call__(self, *args, **kwargs):
self.called = True
self.func(*args, **kwargs)
@with_called_attribute
def run_some_thing(*args, **kwargs):
print("You called with:", *args, **kwargs)
run_some_thing.called
#>>> False
run_some_thing(10)
#>>> You called with: 10
run_some_thing.called
#>>> True
You can use a global
variable and set it to True
inside the function you want to check: 您可以使用
global
变量并将其设置为要检查的函数内的True
:
global hasRun
hasRun = False
def foo():
global hasRun
hasRun = True
def goop():
global hasRun
if hasRun == False:
#Do something if it hasn't run
In your code: 在您的代码中:
global hasRun
hasRun = False
def LoadTable():
global hasRun
doStuff()
hasRun = True
def IsInitialized():
global hasRun
return hasRun #Returns False if hasRun = False, and vice-versa
You need to check for object equality and use a flag to indicate the result. 您需要检查对象是否相等,并使用标志来指示结果。
eg 例如
class Detector(object):
__init__(self):
self.loadTableIsCalledForObjA = False
detector = Detector()
def isInitialized():
if detector.loadTableIsCalledForObjA:
return False
def loadTable(someObj):
if type(someObj) is ObjA:
detector.loadTableIsCalledForObjA = True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.