python+requests+unittest 搭建接口自动化测试框架(二)
入口文件 runAll.py
import os import sys sys.path.append(os.getcwd()) import HTMLTestRunner import unittest import readConfig from common.configEmail import SendEmail send_mail = SendEmail( username='xxxx@qq.com', passwd='gsveeerazxbbaldbgbj', recv=['rrrrrrr@163.com'], title='接口自动化测试', content='测试发送邮件', file='d:/test_interface/report/report.html', ssl=True ) on_off = readConfig.ReadConfig().get_email('on_off') # log = common.Log.logger class AllTest(object):#定义一个类AllTest def __init__(self):#初始化一些参数和数据 self.resultPath = os.path.join(os.getcwd()+'/report/'+'report.html')#result/report.html self.caseListFile = os.path.join(os.getcwd()+'/caselist.txt')#配置执行哪些测试文件的配置文件路径 self.caseFile = os.path.join(os.getcwd()+'/testCase')#真正的用例存放路径 self.caseList = [] def set_case_list(self): """ 读取caselist.txt文件中的用例名称,并添加到caselist元素组 :return: """ fb = open(self.caseListFile) for value in fb.readlines(): if value != '' and '#' not in value:# 如果data非空且不以#开头 self.caseList.append(value.replace("\n", ""))#读取每行数据会将换行转换为\n,去掉每行数据中的\n fb.close() def set_case_suite(self): """ :return: """ self.set_case_list()#通过set_case_list()拿到caselist元素组 test_suite = unittest.TestSuite() for case in self.caseList:#从caselist元素组中循环取出case case_name = case.split("/")[1]#通过split函数来将aaa/bbb分割字符串,1取后面,0取前面 print(case_name+".py")#打印出取出来的名称 #批量加载用例,第1个参数为用例存放路径,第2个参数为用例文件名 discover = unittest.defaultTestLoader.discover(self.caseFile, pattern=case_name + '.py', top_level_dir=None) #使用addTest添加到测试集 test_suite.addTest(discover) return test_suite #返回测试集 def run(self): try: suit = self.set_case_suite()#调用set_case_suite获取test_suite print('try') if suit is not None:#判断test_suite是否为空 fp = open(self.resultPath, 'wb')#打开result/20181108/report.html测试报告文件,如果不存在就创建 #调用HTMLTestRunner runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='Test Report', description='Test Description') runner.run(suit) else: print("Have no case to test.") except Exception as ex: print(str(ex)) #log.info(str(ex)) finally: print("*********TEST END*********") #log.info("*********TEST END*********") fp.close() #判断邮件发送的开关 if on_off != 'on': send_mail.send_email() else: print("邮件发送开关配置关闭,请打开开关后可正常自动发送测试报告") if __name__ == '__main__': AllTest().run()
caselist.txt
user/test01case
#user/test02case
#user/test03case
#user/test04case
#user/test05case
#shop/test_shop_list
#shop/test_my_shop
#shop/test_new_shop