如何判断是否在Python中调用了函数?

时间:2014-04-11 23:29:19

标签: python testing

我是第一次写单元测试,而且我很难绕过这个。我有一个方法IsInitialized(),如果另一个方法LoadTable()为该对象调用了 never ,则该方法应该返回false。如何编写测试方法来验证这一点?

3 个答案:

答案 0 :(得分:3)

为了简单起见,我会把它作为一个属性:

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

答案 1 :(得分:1)

您可以使用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

在您的代码中:

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

答案 2 :(得分:0)

您需要检查对象是否相等,并使用标志来指示结果。

e.g。

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