unittest接口自动化测试

更新时间:2023-07-06 19:11:11 阅读: 评论:0

unittest接⼝⾃动化测试
我⼜来了,来分享年前的unittest接⼝⾃动化实战啦。这次⾃动化接⼝框架⽐较简单,但是五脏俱全。(注:项⽬是针对我们公司内部系统的测试,我就不分享链接了。)项⽬简介
项⽬名称:****名⽚系统
项⽬⽬的:实现系统项⽬⾃动化测试执⾏
项⽬版本:v1.0
项⽬⽬录
tools  #存放辅助⽅法
configEmail.py  #发送测试报告电⼦邮件
  HTMLTestRunner.py #第三⽅插件
  log.py #输出⽇志⽂件
  #存放接收⼈邮箱地址
  read_json.py #读取单⼀测试数据json⽂件
  read_more_json #读取more测试数据json⽂件
施丹旖report #存放html测试报告
logs  #存放输⼊⽇志⽂件
data  #存放参数化测试数据(json⽂件)
ca  #存放测试⽤例
api  #存放封装测试⽅法
<    #存放要执⾏的测试⽤例
getpathInfo.py    #获取当前路径
runAll.py    #运⾏中的测试⽤例,输出测试报告 
项⽬框架
unittest单元测试框架
项⽬设计
1.每⼀个⽤例组合在⼀个测试类⾥⾯⽣成⼀个py⽂件
2.⼀个模块(被测项⽬功能)对应⼀个py⽂件及⼀个测试类(测试⽂件)
3.通过 parameterized 对参数进⾏参数化
项⽬⽬标
1. ⽣成测试⽤例执⾏结果报告
2.⽣成测试⽤例执⾏⽇志
3.⽤例执⾏失败或者执⾏完成后⾃动发送邮件报告
4.数据驱动(读取测试数据,减少脚本维护成本)
项⽬代码
getpathInfo.py  #获取当前路径
import os
def get_Path():
#获取上级路径
#path = os.path.abspath(os.path.wd(), ".."))
#获取当前路径
path = os.path.split(alpath(__file__))[0]
return path
if__name__ == '__main__':# 执⾏该⽂件,测试下是否OK
print('测试路径是否OK,路径为:', get_Path())
getpathInfo.py
investigate
<  #存放可执⾏测试⽤例
runAll.py  #运⾏⽂件
import os
import time
from BeautifulReport import BeautifulReport
import getpathInfo
import tools.HTMLTestRunner as HTMLTestRunner
import unittest
figEmail import nd_email, getReceiverInfo
import tools.Log
path = _Path()
report_path = os.path.join(path, 'report')
log = tools.Log.logger
class AllTest:#定义⼀个类AllTest
def__init__(lf):#初始化⼀些参数和数据
global resultPath
resultPath = os.path.join(report_path)
lf.caListFile = os.path.join(path, "")#配置执⾏哪些测试⽂件的配置⽂件路径
lf.caFile = os.path.join(path, "ca")#真正的测试断⾔⽂件路径
lf.caList = []
log.info('resultPath'+resultPath)#将resultPath的值输⼊到⽇志,⽅便定位查看问题
log.info('caListFile'+lf.caListFile)#同理
log.info('caList'+str(lf.caList))#同理
def t_ca_list(lf):
"""
读取⽂件中的⽤例名称,并添加到calist元素组
:return:
"""新东方英语听力下载
fb = open(lf.caListFile)
for value adlines():
data = str(value)
if data != ''and not data.startswith("#"):# 如果data⾮空且不以#开头
lf.caList.place("\n", ""))#读取每⾏数据会将换⾏转换为\n,去掉每⾏数据中的\n
fb.clo()
def t_ca_suite(lf):
"""
:return:
"""
lf.t_ca_list()#通过t_ca_list()拿到calist元素组
test_suite = unittest.TestSuite()
suite_module = []
for ca in lf.caList:#从calist元素组中循环取出ca
ca_name = ca.split("/")[-1]#通过split函数来将aaa/bbb分割字符串,-1取后⾯,0取前⾯print(ca_name+".py")#打印出取出来的名称
#批量加载⽤例,第⼀个参数为⽤例存放路径,第⼀个参数为路径⽂件名
discover = unittest.defaultTestLoader.discover(lf.caFile, pattern=ca_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)
el:
print('el:')
return None
return test_suite#返回测试集
去日本留学的条件def run(lf):
"""
run test
:return:
"""
try:
suit = lf.t_ca_suite()#调⽤t_ca_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'\report'+ currTime + '.html'
result = BeautifulReport(suit)
# 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)
el:
print("Have no ca to test.")
except Exception as ex:
print(str(ex))
#log.info(str(ex))
finally:
print("*********TEST END*********")
#log.info("*********TEST END*********")
#fp.clo()
#发送测试邮件
# read_msg = getReceiverInfo(
#    r'F:\python_test\Automation_interfaceTest\tools\')
# ndmail = nd_email(read_msg)
# ndmail.ndEmail(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()
runall.py
tools  #辅助⽅法
configEmail.py  # 发送邮件
import os
import smtplib
有道在线翻译器import getpathInfo
from tools.Log import Logger
from import MIMEText
from email.header import Header
log = Logger(__name__)
path = _Path()
report_path = os.path.join(path, 'report')  # 存放测试报告⽂件的路径
mail_path = os.path.join(path,'tools')#存放收件⼈地址⽂件路径
class nd_email():
'''
邮件配置信息
'''
def__init__(lf,
receiver,
subject='*******',
rver='',
fromur='******',
frompassword='yjkxwfmrbumrbbce',
nder='*******'):
"""
:param receiver:
:param subject:
:
param rver:
:param fromur:
:param frompassword:
:param nder:
"""
lf._rver = rver
lf._fromur = fromur
lf._frompassword = frompassword
lf._nder = nder
lf._receiver = receiver
lf._subject = subject
def ndEmail(lf, fileName):
"""
:param filename:
:return:
"""
whispering#  打开报告⽂件读取⽂件内容
try:
f = open(os.path.join(report_path, fileName), 'rb')
fileMsg = f.read()
except Exception:
ption(
'open or read file [%s] failed,No such file or directory: %s' % (fileName, report_path))
log.logger.info('open and read file [%s] succesd!' % fileName)
el:
f.clo()
#  邮件主题
subject = 'Python test report'#
#  邮件设置
msg = MIMEText(fileMsg, 'html', 'utf-8')
msg['subject'] = Header(subject, 'utf-8')
msg['from'] = lf._nder
#  连接服务器,登录服务器,发送邮件
try:
smtp = smtplib.SMTP()
smtp.login(lf._fromur, lf._frompassword)
except Exception:
ption('connect [%s] rver failed or urname and password incorrect!' % smtp) el:
log.logger.info('email rver [%s] login success!' % smtp)
try:
smtp.ndmail(lf._nder, lf._receiver, msg.as_string())
except Exception:
ption('nd email failed!')
el:
log.logger.info('nd email succesd!')
#  从⽂件中读取邮件接收⼈信息
def getReceiverInfo(fileName):
'''
:param filename: 读取接收邮件⼈信息
:return: 接收邮件⼈信息
'''
try:
openFile = open(os.path.join(mail_path, fileName))
except Exception:
ption('open or read file [%s] failed,No such file or directory: %s' % (fileName, mail_path)) el:
log.logger.info('open file [%s] succesd!' % fileName)
for line in openFile:
msg = [i.strip() for i in line.split(',')]
log.logger.info('reading [%s] and got receiver value is [%s]' % (fileName, msg))
return msg
if__name__ == '__main__':# 运营此⽂件来验证写的nd_email是否正确
readMsg = getReceiverInfo('')
ndmail = nd_email(readMsg)
ndmail.ndEmail('report.html')
configEmail.py
HTMLTestRunner.py #第三⽅插件
log.py #输出⽇志⽂件
import os
import logging
坐地虎import time
from logging.handlers import TimedRotatingFileHandler
import getpathInfo
path = _Path()
log_path = os.path.join(path, 'logs')  # 存放log⽂件的路径
class Logger(object):
def__init__(lf, logger_name='logs…'):
lf.logger = Logger(logger_name)
currTime = time.strftime("%Y-%m-%d")
lf.log_file_name = currTime+'logs'# ⽇志⽂件的名称
lf.backup_count = 5  # 最多存放⽇志的数量
# ⽇志输出级别
lf.file_output_level = 'DEBUG'
# ⽇志输出格式
lf.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
def get_logger(lf):
"""在logger中添加⽇志句柄并返回,如果logger已有句柄,则直接返回"""
if not lf.logger.handlers:  # 避免重复⽇志
console_handler = logging.StreamHandler()
console_handler.tFormatter(lf.formatter)
console_handler.sole_output_level)
lf.logger.addHandler(console_handler)
# 每天重新创建⼀个⽇志⽂件,最多保留backup_count份
file_handler = TimedRotatingFileHandler(filename=os.path.join(log_path, lf.log_file_name), when='D',                                                    interval=1, backupCount=lf.backup_count, delay=True,
encoding='utf-8')
file_handler.tFormatter(lf.formatter)
file_handler.tLevel(lf.file_output_level)
lf.logger.addHandler(file_handler)
return lf.logger
logger = Logger().get_logger()
log.py
   #存放接受⼈邮箱地址
 read_json.py  # 读取单⼀测试数据
import json
import getpathInfo
import os
class ReadJson(object):
def__init__(lf,filename):
path = _Path()
lf.filepath = os.path.join(path, 'data')+"/"+filename
def read_json(lf):
with open(lf.filepath, "r", encoding="utf-8")as f:
# 调⽤load⽅法加载⽂件流
return json.load(f)
if__name__ == '__main__':
data = ReadJson("updateurpwd.json").read_json()
arrs = []
arrs.append((("url"),
<("urId"),
<("data"),
<("success"),
<("message")))
print(arrs)
read_json.py
 read_more_json.py  # 读取more测试数据
import json
class ReadJson(object):
def__init__(lf,filename):
lf.filepath = '../data/' +filename
def read_json(lf):
with open(lf.filepath, "r", encoding="utf-8")as f:
# 调⽤load⽅法加载⽂件流
return json.load(f)
if__name__ == '__main__':
datas = ReadJson("login_more.json").read_json()
arrs = []
for data in datas.values():
arrs.append((("url"),
<("mobile"),
<("code"),
<("expect_result"),
<("status_code")))
print(arrs)
read_more_json.py
#测试⽤例
import requests
class ApiLogin(object):
def api_post_login(lf,data):
#headers定义
headers = {"Content-Type": "application/x-www-form-urlencoded"} #url定义
url = "*******"
#调⽤post返回相应对象
return requests.post(url, headers=headers,data = data)
api_login.py
#客户经理登录接⼝
import sys
import unittest
from api.api_login import ApiLogin
from parameterized import parameterized
ad_more_json  import ReadJson
import tools.Log
log = tools.Log.logger
#读取数据函数
def get_data():
datas = ReadJson('login.json').read_json()
arrs = []
barristerfor data in datas.values():
arrs.append((("data"),
<("message"),
<("desc")))
return arrs
happening
class TestLogin(unittest.TestCa):
'''登录接⼝ '''
@pand(get_data())  # 参数化测试⽤例
def test_login(lf,data,message,desc):
#调⽤登录⽅法
s = ApiLogin().api_post_login(data)
#调试使⽤添加描述
lf._testMethodDoc = desc
#print('查看响应结果:',s.text)
#断⾔响应信息
目录英文lf.asrtIn()
# ⽣成响应⽇志
log.info('[%s]响应数据为:[%s]' % (sys._getframe()._name, s.text))
if__name__ == '__main__':
unittest.main()
test_login.py
#测试数据
{
"login_001":{
"data":{"loginName":"admin", "password": "123456","memberPass": "on"},
"message": "名⽚管理系统",
"desc": "正常登录"},
"login_002": {
"data":{"loginName":"admin", "password": "123456n","memberPass": "on"},
"message": "密码不正确",
"desc": "账号错误登录"},
"login_003": {
"data":{"loginName":"admir", "password": "123456","memberPass": "on"},
"message": "账号不存在",
"desc": "密码错误登录"},
"login_004": {
"data":{"loginName":"", "password": "123456","memberPass": "on"},
"message": "帐号密码登录",
"desc": "密码为空登录"},
"login_005": {
"data":{"loginName":"admin", "password": "","memberPass": "on"},
"message": "密码不正确",
"desc":"账号为空登录"},
"login_006": {
"data":{"loginName":"adm in", "password": "123456","memberPass": "on"},
"message": "账号不存在",
"desc":"账号存在空格登录"},
"login_007": {
"data":{"loginName":"admin", "password": "123 456","memberPass": "on"},
"message": "密码不正确",
"desc":"密码存在空格登录"},
"login_008": {
"data":{"loginName":"admin.", "password": "123456","memberPass": "on"},
"message": "账号不存在",
"desc":"账号存在特殊符号登录"},
"login_009": {

本文发布于:2023-07-06 19:11:11,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/78/1082276.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:测试   邮件   存放   登录   读取
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图