以数据驱动的形式,将用例维护在py文件中
源码分析:
变量定义
publicParameters.py
""" 公共参数 , 按照各公司实情,自行编写 """ url = "https://XXXX.com" username = "XXXXXXX" password = XXXX tenantId = XXXX passport_id = XXXX encryptionKey = XXXX # 请求参数类型 getType = 'get' postType = 'post'
参数定义
login.py
from . import publicParameters # 接口信息 API_ALL = { '登录接口': { 'number': '1', 'url': publicParameters.url + "xxxxxxxx", 'type': publicParameters.postType, 'head': { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36' }, 'body': { "loginName": "%s" % publicParameters.username, "password": "%s" % publicParameters.password, "pcCodeForFocusMedia": 0 }, 'assert': { 'status': 202, }, }, '选择租户接口': { 'number': '2', 'url': publicParameters.url + "xxxxxxxx", 'type': publicParameters.postType, 'head': { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36' }, 'body': { "tenantId": "%s" % publicParameters.tenantId, "passport.id": publicParameters.passport_id, "encryptionKey": "%s" % publicParameters.encryptionKey, "loginName": "%s" % publicParameters.username }, 'assert': { 'status': 0, }, } }
执行工具类
test.py
import requests import time from autoTest.Api_test.common.login import API_ALL from autoTest.Api_test.page.Log import Log def Script(): log = Log() # 引用日志方法 apikeys = API_ALL.keys() # 获取所有Api参数 if apikeys: for key in apikeys: apiname = key url = API_ALL[key]['url'] number = API_ALL[key]['number'] type = API_ALL[key]['type'] body = API_ALL[key]['body'] assertDate = API_ALL[key]['assert']['status'] if type == 'post': log.info("======="+" api名称:" + apiname + "=======") data = requests.post(url=url, data=body, verify=False) log.info(data.json()) if assertDate == data.json()['status']: testCode = str(data.status_code) Time = str(data.elapsed.microseconds) log.info("执行编号:" + number + " 响应code:" + testCode + " 响应时间:" + Time + " 请求类型:" + type + " 请求参数:" + str(body)) else: log.error("接口返回异常, status=%s" % data.json()['status']) time.sleep(1) if type == 'get': log.info("======="+" api名称:" + apiname + "=======") data = requests.get(url=url, data=body, verify=False) log.info(data.json()) if assertDate == data.json()['status']: testCode = str(data.status_code) Time = str(data.elapsed.microseconds) log.info("执行编号:" + number + " 响应code:" + testCode + " 响应时间:" + Time + " 请求类型:" + type + " 请求参数:" + str(body)) else: log.error("接口返回异常, status=%s" % data.json()['status']) time.sleep(1) else: log.error("数据不存在")
unittest执行类
testCase.py
import unittest import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning # 禁用安全请求警告 requests.packages.urllib3.disable_warnings(InsecureRequestWarning) from autoTest.Api_test.ApiTest import test class testclassone(unittest.TestCase): def setUp(self): print("setUp") pass def test_1(self): # 执行脚本 test.Script() pass def tearDown(self): print("tearDown") pass if __name__ == '__main__': unittest.main()
最后,我们还可以批量执行case
# coding=utf-8 import unittest import time from autoTest.autoTestAPI import HTMLTestRunner_jpg from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import smtplib import os ''' #### 下面三行代码python2报告出现乱码时候可以加上#### import sys reload(sys) sys.setdefaultencoding('utf8') ''' # 这个是优化版执行所有用例并发送报告,分四个步骤 # 第一步加载用例 # 第二步执行用例 # 第三步获取最新测试报告 # 第四步发送邮箱 (这一步不想执行的话,可以注释掉最后面那个函数就行) # 当前脚本所在文件真实路径 cur_path = os.path.dirname(os.path.realpath(__file__)) def add_case(caseName="case", rule="test*.py"): '''第一步:加载所有的测试用例''' case_path = os.path.join(cur_path, caseName) # 用例文件夹 # 如果不存在这个case文件夹,就自动创建一个 if not os.path.exists(case_path):os.mkdir(case_path) print("test case path:%s"%case_path) # 定义discover方法的参数 discover = unittest.defaultTestLoader.discover(case_path, pattern=rule, top_level_dir=None) print(discover) return discover def run_case(all_case, reportName="report"): '''第二步:执行所有的用例, 并把结果写入HTML测试报告''' now = time.strftime("%Y_%m_%d_%H_%M_%S") report_path = os.path.join(cur_path, reportName) # 用例文件夹 # 如果不存在这个report文件夹,就自动创建一个 if not os.path.exists(report_path):os.mkdir(report_path) report_abspath = os.path.join(report_path, "result.html") print("report path:%s"%report_abspath) fp = open(report_abspath, "wb") runner = HTMLTestRunner_jpg.HTMLTestRunner(stream=fp, title=u'自动化测试报告,测试结果如下:', description=u'用例执行情况:', retry=1 # 失败重跑 ) # 调用add_case函数返回值 runner.run(all_case) fp.close() def get_report_file(report_path): '''第三步:获取最新的测试报告''' lists = os.listdir(report_path) lists.sort(key=lambda fn: os.path.getmtime(os.path.join(report_path, fn))) print (u'最新测试生成的报告: '+lists[-1]) # 找到最新生成的报告文件 report_file = os.path.join(report_path, lists[-1]) return report_file def send_mail(sender, psw, receiver, smtpserver, report_file, port): '''第四步:发送最新的测试报告内容''' with open(report_file, "rb") as f: mail_body = f.read() # 定义邮件内容 now_time = time.strftime("%Y-%m-%d %H:%M:%S") msg = MIMEMultipart() body = MIMEText(mail_body, _subtype='html', _charset='utf-8') msg['Subject'] = u"自动化测试报告_%s"%now_time msg["from"] = sender msg["to"] = "".join(receiver) # 只能字符串 msg.attach(body) # 添加附件 att = MIMEText(open(report_file, "rb").read(), "base64", "utf-8") att["Content-Type"] = "application/octet-stream" att["Content-Disposition"] = 'attachment; filename= "report.html"' msg.attach(att) try: smtp = smtplib.SMTP() smtp.connect(smtpserver) # 连服务器 smtp.login(sender, psw) except: smtp = smtplib.SMTP_SSL(smtpserver, port) smtp.login(sender, psw) # 登录 smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() print('test report email has send out !') if __name__ == "__main__": all_case = add_case() # 1加载用例 # # 生成测试报告的路径 run_case(all_case) # 2执行用例 # # 获取最新的测试报告文件 report_path = os.path.join(cur_path, "report") # 用例文件夹 report_file = get_report_file(report_path) # 3获取最新的测试报告 # #邮箱配置 sender = "xxxxxx" psw = "xxxxx" smtp_server = "smtp.163.com" port = 465 receiver = ['xxxxxx'] send_mail(sender, psw, receiver, smtp_server, report_file, port) # 4最后一步发送报告
当然缺少HTMLTestRunner_jpg文件的同学,可以百度自行下载(找个好看的)
到这,一个简单的ddt就完成了, 是不是很简单? 哈哈, 中午休息时间,写了代码,又完成了一篇博客, 6666
作者:含笑半步颠√
博客链接:https://www.cnblogs.com/lixy-88428977
声明:本文为博主学习感悟总结,水平有限,如果不当,欢迎指正。如果您认为还不错,欢迎转载。转载与引用请注明作者及出处。