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. 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 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.