通过装饰器处理每个步骤的结果
#autotest.py
import threading
import time
def stepresult(step_number,expect=""):
def wrapper(fun):
def inner(*args,**kwargs):
step={}
result="PASS"
step["step_number"]= step_number
print(f"expect{expect},{step_number}")
try:
start=time.time()
ret=fun(*args,**kwargs)
except Exception as e:
result="FAIL"
step["error"]= e
ret='0'
Collector().add_case_result(result)
end=time.time()-start
step["step_result"]=result
step["step_run_time"]=end
Collector().add_step_result(step)
return ret
return inner
return wrapper
class Collector:
_instance_lock = threading.Lock()
init=False
def __new__(cls,*args,**kwargs):
if not hasattr(cls,"_instance"):
with cls._instance_lock:
if not hasattr(cls, '_instance'):
cls._instance=object.__new__(cls,)
return cls._instance
def __init__(self):
if Collector.init == True:
return
Collector.init =True
self.Result="PASS"
self.stepresult=[]
self.step={"step_number":"","step_result":"","time":""}
self.caseresult={"case result":"PASS","step detail":self.stepresult,"total time":""}
def add_step_result(self,stepresult):
print(stepresult)
self.stepresult.append(stepresult)
def add_case_result(self,result):
self.caseresult["case result"]=result
def add_case_time(self,time):
self.caseresult["total time"]=time
def get_result(self):
return self.caseresult
2. 所有的case 脚本 需要继承 CaseModle类
#case_modle.py
from autotest import Collector, stepresult
import time
class CaseModle():
def __init__(self):
pass
def set_up(self):
print("set_up")
@stepresult(1, expect="wwww")
def step_1(self):
print("step 1")
@stepresult(2,"333")
def step_2(self):
time.sleep(1)
print("step2")
def tear_down(self):
print("tear_dowm")
def main(self):
print("main")
self.step_1()
self.step_2()
def run(self):
print("run")
start = time.time()
try:
self.set_up()
self.main()
self.tear_down()
except Exception as e:
Collector().add_case_result("fail")
end = time.time() - start
Collector().add_case_time(end)
print(Collector().get_result())
3.casedemo
#casedemo.py from case_modle import CaseModle,stepresult import time class Case(CaseModle): def set_up(self): print("child setup") @stepresult(1) def step_1(self): time.sleep(3) print("child step 1") @stepresult(2,"33333") def step_2(self,a): time.sleep(3) print("child step2") assert a>10 def main(self): print("child main") self.step_2(12) self.step_1() def tear_down(self): print("child teardown") # raise if __name__=="__main__": Case().run()