以数据驱动的形式,将用例维护在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测试的更多相关文章

  1. python+requests实现接口自动化

    1. 前言 今年2月调去支持项目接口测试,测试过程中使用过postman.jmeter工具,基本能满足使用,但是部分情况下使用较为麻烦.比如:部分字段存在唯一性校验或字段间有业务性校验,每次请求均需手 ...

  2. python+requests+unittest执行自动化接口测试

    1.安装requests.xlrd.json.unittest库 <1>pip 命令安装: pip install requestspip install xlrdpip install ...

  3. 使用python+requests+unittest实现接口自动化测试

    这两天一直在找直接用python做接口自动化的方法,在网上也搜了一些博客参考,今天自己动手试了一下. 一.整体结构 上图是项目的目录结构,下面主要介绍下每个目录的作用. Common:公共方法:主要放 ...

  4. Python+requests+unittest+excel实现接口自动化测试框架

    一.框架结构:  工程目录 二.Case文件设计 三.基础包 base 3.1 封装get/post请求(runmethon.py) import requests import json class ...

  5. Python+requests+unittest+excel实现接口自动化测试框架(摘录)

    一.框架结构:  工程目录 二.Case文件设计 三.基础包 base 3.1 封装get/post请求(runmethon.py) 1 import requests 2 import json 3 ...

  6. Python+requests+unittest+excel实现接口自动化测试框架(转

    一.框架结构:工程目录 二.Case文件设计三.基础包 base 3.1 封装get/post请求(runmethon.py) import requests import json class Ru ...

  7. python+requests+unittest API接口测试

    黑熊再网上查找了下接口测试相关的资料,大都重点是以数据驱动的形式,见用例维护在文本或表格中,而没有说明怎么样去生成想要的用例, 问题: 测试接口时,比如参数a,b,c,我要先测a参数,有(不传,为空, ...

  8. python requests简单接口自动化

    get方法 url:显而易见,就是接口的地址url啦 headers:定制请求头(headers),例如:content-type = application/x-www-form-urlencode ...

  9. 利用 python requests完成接口文件上传

    最近在准备一个公开课,主题就是利用不同的语言和不同的工具去实现文件的上传和下载. 在利用Jmeter去实现功能的时候,以及利用loadrunner去写脚本的时候,都很顺利,没有任何问题,当我尝试用Py ...

随机推荐

  1. 为什么MES实施起来效果不佳?

    原因一:我国制造业存在管理基础的先天不足 我国企业与发达国家企业在管理发展上,存在较大的差别.发达制造国家经历了管理探索.发展.成熟.再提高的全过程,从管理基础的奠定到思想认识的深刻程度,都是我国所无 ...

  2. FPM十一:点击POPUP显示明细

    沿接着前面的Search和List.在LIST中点击一列,弹出窗口显示明细. 1.list中定义事件: METHOD if_fpm_guibb_list~get_definition. DATA:gt ...

  3. Matplotlib 绘制定制的直方图

    1.普通风格 代码 import numpy as np import matplotlib.pyplot as plt rng = np.random.RandomState(27) x = rng ...

  4. UGUI:技能冷却效果

    版权申明: 本文原创首发于以下网站: 博客园『优梦创客』的空间:https://www.cnblogs.com/raymondking123 优梦创客的官方博客:https://91make.top ...

  5. 机器取代人类成为现实,Linux shell才可被取代?

    机器取代人类成为现实,Linux shell才可被取代? 新睿云 新睿云 新睿云-让云服务触手可及 本次笔者用通俗易懂的语言介绍一下Linux shell,由于笔者能力有限,如有有描述不准确的地方还请 ...

  6. IE、chrome驱动下载地址

    http://selenium-release.storage.googleapis.com/index.html IE驱动https://sites.google.com/a/chromium.or ...

  7. VMware下安装Ubuntu虚拟机

    ubuntu系统是以桌面应用为主的.当下最火的linux操作系统,具有实用的界面,并且完全免费. 在Ubuntu的 Linux 世界里,已经不再只是简陋的界面+命令行,而是一款华丽时尚且无比实用的操作 ...

  8. JDK9下载与安装

    1.进入oracle官网下载页面 https://www.oracle.com/downloads/index.html 2.点击Menu 3.点击JAVA SE 4.点击JDK Download 5 ...

  9. css 布局 一中一右

    .container { position: relative; .my-center { text-align: center; line-height: 30rpx; min-width: 400 ...

  10. (HK1-0)激活与配置摄像机

    HK使用手册 网络连接 激活与配置摄像机 网络摄像机可通过 SADP 软件.客户端软件和浏览器三种方式激活, 具体激活操作方式可参见<网络摄像机操作手册>. 1. 安装随机光盘或从官网下载 ...