unittest接口自动化测试
我又来了,来分享年前的unittest接口自动化实战啦。这次自动化接口框架比较简单,但是五脏俱全。(注:项目是针对我们公司内部系统的测试,我就不分享链接了。)
项目简介
项目名称:****名片系统
项目目的:实现系统项目自动化测试执行
项目版本:v1.0
项目目录
tools #存放辅助方法
configEmail.py #发送测试报告电子邮件 HTMLTestRunner.py #第三方插件 log.py #输出日志文件 mail_receiver.txt #存放接收人邮箱地址 read_json.py #读取单一测试数据json文件 read_more_json #读取more测试数据json文件
report #存放html测试报告
logs #存放输入日志文件
data #存放参数化测试数据(json文件)
case #存放测试用例
api #存放封装测试方法
caselist.txt #存放要执行的测试用例
getpathInfo.py #获取当前路径
runAll.py #运行caselist.txt中的测试用例,输出测试报告
项目框架
unittest单元测试框架
项目设计
1.每一个用例组合在一个测试类里面生成一个py文件
2.一个模块(被测项目功能)对应一个py文件及一个测试类(测试文件)
3.通过 parameterized 对参数进行参数化
项目目标
1. 生成测试用例执行结果报告
2.生成测试用例执行日志
3.用例执行失败或者执行完成后自动发送邮件报告
4.数据驱动(读取测试数据,减少脚本维护成本)
项目代码
getpathInfo.py #获取当前路径
import os def get_Path(): #获取上级路径 #path = os.path.abspath(os.path.join(os.getcwd(), "..")) #获取当前路径 path = os.path.split(os.path.realpath(__file__))[0] return path if __name__ == '__main__':# 执行该文件,测试下是否OK print('测试路径是否OK,路径为:', get_Path())
caselist.txt #存放可执行测试用例
runAll.py #运行文件
import os import time from BeautifulReport import BeautifulReport import getpathInfo import tools.HTMLTestRunner as HTMLTestRunner import unittest from tools.configEmail import send_email, getReceiverInfo import tools.Log path = getpathInfo.get_Path() report_path = os.path.join(path, 'report') log = tools.Log.logger class AllTest:#定义一个类AllTest def __init__(self):#初始化一些参数和数据 global resultPath resultPath = os.path.join(report_path) self.caseListFile = os.path.join(path, "caselist.txt")#配置执行哪些测试文件的配置文件路径 self.caseFile = os.path.join(path, "case")#真正的测试断言文件路径 self.caseList = [] log.info('resultPath'+resultPath)#将resultPath的值输入到日志,方便定位查看问题 log.info('caseListFile'+self.caseListFile)#同理 log.info('caseList'+str(self.caseList))#同理 def set_case_list(self): """ 读取caselist.txt文件中的用例名称,并添加到caselist元素组 :return: """ fb = open(self.caseListFile) for value in fb.readlines(): data = str(value) if data != '' and not data.startswith("#"):# 如果data非空且不以#开头 self.caseList.append(data.replace(" ", ""))#读取每行数据会将换行转换为 ,去掉每行数据中的 fb.close() def set_case_suite(self): """ :return: """ self.set_case_list()#通过set_case_list()拿到caselist元素组 test_suite = unittest.TestSuite() suite_module = [] for case in self.caseList:#从caselist元素组中循环取出case case_name = case.split("/")[-1]#通过split函数来将aaa/bbb分割字符串,-1取后面,0取前面 print(case_name+".py")#打印出取出来的名称 #批量加载用例,第一个参数为用例存放路径,第一个参数为路径文件名 discover = unittest.defaultTestLoader.discover(self.caseFile, pattern=case_name + '.py', top_level_dir=None) suite_module.append(discover)#将discover存入suite_module元素组 print('suite_module:'+str(suite_module)) if len(suite_module) > 0:#判断suite_module元素组是否存在元素 for suite in suite_module:#如果存在,循环取出元素组内容,命名为suite for test_name in suite:#从discover中取出test_name,使用addTest添加到测试集 test_suite.addTest(test_name) else: print('else:') return None return test_suite#返回测试集 def run(self): """ run test :return: """ try: suit = self.set_case_suite()#调用set_case_suite获取test_suite print('try') print(str(suit)) if suit is not None:#判断test_suite是否为空 print('if-suit') currTime = time.strftime('%Y-%m-%d %H_%M_%S') filename = currTime + '.html' # currTime = time.strftime('%Y-%m-%d %H_%M_%S') # fileName = report_path + r' eport'+ currTime + '.html' result = BeautifulReport(suit) result.report(filename= filename, description='接口测试报告') # fp = open(fileName, 'wb') # runner = HTMLTestRunner.HTMLTestReportCN # (stream=fp, title='自动化接口测试报告', # description='处理器:Intel(R) Core(TM) ' # 'i5-5200U CPU @ 2.20GHz 2.20 GHz ' # '内存:8G 系统类型: 64位 版本: windows 10 专业版') # 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() #发送测试邮件 # read_msg = getReceiverInfo( # r'F:python_testAutomation_interfaceTest oolsmail_receiver.txt') # sendmail = send_email(read_msg) # sendmail.sendEmail(fileName) # pythoncom.CoInitialize() # scheduler = BlockingScheduler() # scheduler.add_job(AllTest().run, 'cron', day_of_week='1-5', hour=14, minute=59) # scheduler.start() if __name__ == '__main__': AllTest().run()