python+requests+unittest 接口ddt测试
以数据驱动的形式,将用例维护在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': '',
'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': '',
'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
声明:本文为博主学习感悟总结,水平有限,如果不当,欢迎指正。如果您认为还不错,欢迎转载。转载与引用请注明作者及出处。
python+requests+unittest 接口ddt测试的更多相关文章
- python+requests实现接口自动化
1. 前言 今年2月调去支持项目接口测试,测试过程中使用过postman.jmeter工具,基本能满足使用,但是部分情况下使用较为麻烦.比如:部分字段存在唯一性校验或字段间有业务性校验,每次请求均需手 ...
- python+requests+unittest执行自动化接口测试
1.安装requests.xlrd.json.unittest库 <1>pip 命令安装: pip install requestspip install xlrdpip install ...
- 使用python+requests+unittest实现接口自动化测试
这两天一直在找直接用python做接口自动化的方法,在网上也搜了一些博客参考,今天自己动手试了一下. 一.整体结构 上图是项目的目录结构,下面主要介绍下每个目录的作用. Common:公共方法:主要放 ...
- Python+requests+unittest+excel实现接口自动化测试框架
一.框架结构: 工程目录 二.Case文件设计 三.基础包 base 3.1 封装get/post请求(runmethon.py) import requests import json class ...
- Python+requests+unittest+excel实现接口自动化测试框架(摘录)
一.框架结构: 工程目录 二.Case文件设计 三.基础包 base 3.1 封装get/post请求(runmethon.py) 1 import requests 2 import json 3 ...
- Python+requests+unittest+excel实现接口自动化测试框架(转
一.框架结构:工程目录 二.Case文件设计三.基础包 base 3.1 封装get/post请求(runmethon.py) import requests import json class Ru ...
- python+requests+unittest API接口测试
黑熊再网上查找了下接口测试相关的资料,大都重点是以数据驱动的形式,见用例维护在文本或表格中,而没有说明怎么样去生成想要的用例, 问题: 测试接口时,比如参数a,b,c,我要先测a参数,有(不传,为空, ...
- python requests简单接口自动化
get方法 url:显而易见,就是接口的地址url啦 headers:定制请求头(headers),例如:content-type = application/x-www-form-urlencode ...
- 利用 python requests完成接口文件上传
最近在准备一个公开课,主题就是利用不同的语言和不同的工具去实现文件的上传和下载. 在利用Jmeter去实现功能的时候,以及利用loadrunner去写脚本的时候,都很顺利,没有任何问题,当我尝试用Py ...
随机推荐
- github操作
Github使用 1. 注册 官网:https://github.com/ 搜索项目 以压缩包的的形式下载demo 克隆项目 创建仓库 克隆项目,编写,完成上传,使用https请求,需要输入用户名 ...
- linux系统盘扩容操作
linux操作系统原来的50硬盘空间不够用了,如果再加一块60G硬盘,怎样扩容呢?今天我参考了前辈门的文档实际操作了一下,涉及到PV/VG/LV的相关操作. 当50G系统硬盘不够,再挂载一块60G,就 ...
- linux 文件上传 linux服务器
1.Linux下目录复制:本机->远程服务器 1 2 scp -r /home/shaoxiaohu/test1 zhidao@192.168.0.1:/home/test2 #test1 ...
- Hive 问题
hive 重启连接不上 异常信息: FAILED: HiveException java.lang.RuntimeException: Unable to instantiate org.apache ...
- linux防止恶意采集攻防战
这两天ytkah开发的一个中大型项目被人盯上了,网站打开非常慢,查看了一下cpu.内存使用情况,30%左右占用不高,网络上下行就比较大了,IO实时流量达到40MB,IO总流量更是7TB,非常大的数据量 ...
- hive使用beeline配置远程连接
hive以hadoop集群为基础,提供hdfs的SQL支持: hive一般可以以mysql为元数据存储,默认Derby:hadoop,hive安装自行百度吧: 介绍hive的远程访问: 未配置之前使用 ...
- Python进阶-I 初识函数(function)
函数 在java中叫方法. 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段. 函数能提高应用的模块性,和代码的重复利用率.你已经知道Python提供了许多内建函数,比如print() ...
- Set学习笔记
今天又去看了一下STL里的set,来这里水一下博客 What is set? set的本质是一种功能受限的平衡树,不支持重复数字,也就是说如果插入一大堆数字12,输出它的长度还是1 如何定义 定义 s ...
- makefile通用版本(三)
DIR_INC = ./include DIR_SRC = ./src DIR_OBJ = ./obj DIR_BIN = ./bin DIR_LIB = -Wl,-rpath=/home/exbot ...
- 在Linux上使用mssql-conf工具配置SQL Server 2017
mssql-conf是在Linux上安装SQL Server 2017后的一个配置脚本.你可以使用这个实用工具设置以下参数: Agent 启用SQL Server代理 Collation 设置一个新的 ...