接口测试框架
本文中只讲到 测试用例 - 用例读取器 - 用例解析器 - 核心运行器 - 结果分析器 - 报告 - 通知
在一个exexl中存放测试用例,通过unittest进行用例读取、解析,并生成测试报告,将报告以邮件形式发送给接收者。 API接口:https://www.sojson.com/blog/234.html(感谢博主提供的免费天气查询的API)
建立一个项目test_API 新建如下文件夹,各文件夹作用如下: case : 存放写有测试用例的execl表 execl : 读取execl的文件 httpop : 通过requests.get获取API数据 report : 生成测试报告 mail : 发送邮件 test : 自动化测试模块 execl表中数据:
代码:
test/my_test.py
import unittest
import json
import jsonpath
from httpop
.httpop
import httpop
from execl
.execlop
import execlop
class Mytestcase(unittest
.TestCase
):
listcheacklist
= []
def setUp(self
):
Mytestcase
.listcheacklist
= execlop
().execlread
()
def test_checklist3(self
):
for checklist
in Mytestcase
.listcheacklist
:
url
= checklist
[0]
expect
= str(checklist
[2])
jsondir
= checklist
[3]
res
= httpop
().api_get
(url
)
res_json
= json
.loads
(res
.content
)
result
= jsonpath
.jsonpath
(res_json
, jsondir
)
print(res_json
)
self
.assertEqual
(expect
,result
[0])
if __name__
== '__main__':
unittest
.main
()
execl/execlop.py
from openpyxl
import load_workbook
import os
class execlop:
def execlread(self
):
listcheacklist
= []
pathdir
= os
.path
.dirname
(__file__
)
path
= pathdir
+ '/../case/case.xlsx'
work_book
= load_workbook
(path
)
sheet
= work_book
['Sheet1']
rows_sheet
= sheet
.iter_rows
()
for item
in rows_sheet
:
if item
[0].value
== 'url':
continue
list = []
for col
in item
:
list.append
(col
.value
)
listcheacklist
.append
(list)
return listcheacklist
httpop/httpop.py
import requests
class httpop:
def api_get(self
,url
):
res
= requests
.get
(url
)
return res
report/report.py
from HTMLTestRunner
import HTMLTestRunner
import unittest
from datetime
import datetime
from mail
.sendmail
import sendmail
class report:
def toReport(self
):
dir_path
= '../test'
discover
= unittest
.defaultTestLoader
.discover
(dir_path
, pattern
= '*.py')
time
= datetime
.now
()
now
= time
.strftime
('%Y-%m-%d %H-%M-%S')
report_path
= now
+ 'result.html'
with open(report_path
, 'wb') as f
:
runner
= HTMLTestRunner
(stream
= f
, verbosity
= 2, title
= '接口测试报告', description
= '用例执行报告')
runner
.run
(discover
)
f
.close
()
sendmail
().send_mail
(report_path
)
if __name__
== '__main__':
report
().toReport
()
报告详情:
mail/sendmail.py
import smtplib
from email
.mime
.text
import MIMEText
class sendmail:
def send_mail(self
, path
):
f
= open(path
, 'rb')
mail_body
= f
.read
()
f
.close
()
'''
465端口(SMTPS):465端口是为SMTPS(SMTP-over-SSL)协议服务开放的,这是SMTP协议基于SSL安全协议之上的一种变种协议,
它继承了SSL安全协议的非对称加密的高度安全可靠性,可防止邮件泄露。SMTPS和SMTP协议一样,也是用来发送邮件的,只是更安全些,
防止邮件被黑客截取泄露,还可实现邮件发送者抗抵赖功能。防止发送者发送之后删除已发邮件,拒不承认发送过这样一份邮件。
'''
host
= 'smtp.163.com'
port
= 465
sender
= '#########@163.com'
pwd
= '###########'
receiver
= '##############'
msg
= MIMEText
(mail_body
, 'HTML', 'UTF-8')
msg
['subject'] = 'API测试报告发送'
msg
['from'] = sender
msg
['to'] = receiver
s
= smtplib
.SMTP_SSL
(host
, port
)
s
.login
(sender
, pwd
)
s
.sendmail
(sender
, receiver
, msg
.as_string
())
邮件详情: