python接口自动化基础框架结构 ——分层
--bin 用于存放启动文件,如run.py
--cases cases目录,存放测试脚本
--data YAML文件
--lib 存放各种附加的代码文件,如加密、链接数据库、生成测试脚本等
--report 存放报告
--setting.py 存放各种路径配置、服务器接口配置等等
--case_template.txt 模板文件,生成测试脚本的模板
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
--setting.py 存放各种路径配置、服务器接口配置等等
import os
#设置目录的绝对路径
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
DATA_PATH = os.path.join(BASE_PATH, 'data') #yaml测试用例存放位置
CASE_PATH = os.path.join(BASE_PATH, "testcase") #测试用例存放位置
REPORT_PATH = os.path.join(BASE_PATH, 'report') #测试报告存放位置
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
--case_template.txt 模板文件,生成测试脚本的模板
#接口自动化模板
import os
import unittest
import requests
from lib.md5_passwd import hash_code
from ddt import ddt,file_data
from lib.set_case_file import set_res_data
from setting import DATA_PATH
@ddt
class %(class_name)s(unittest.TestCase):
@file_data(os.path.join(DATA_PATH, '%(data_file)s.yaml'))
def test_%(method_name)s(self, **casedata):
url = casedata.get('url')
data = casedata.get('data')
method = casedata.get("method")
if "password" in data: #判断是否存在密码
data["password"] = hash_code(data["password"]) # 密码取出后加密传给自身
if method == "post":
result = requests.post(url=url, data=data) #post请求
else:
result = requests.get(url=url, params=data) #get请求
try:
if method.lower()=='post':
res = requests.post(url,data=data)
resp = res.text
else:
res = requests.get(url,params = data)
resp =res.text
except Exception as e:
print("接口请求出错!")
resp = e
asserlist = casedata.get("asserlist")
check = set_res_data(result.text)
for asser in asserlist:
self.assertIn(asser, check)
if __name__ == '__main__':
unittest.main()
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
--bin 用于存放启动文件,如run.py
run.py文件代码
import os
import sys
import unittest
from setting import *
from lib.set_case_file import create_case_file
import time
from BeautifulReport import BeautifulReport as BetRep
#将当前项目的目录加入零时环境变量,避免在其他地方运行时会出现引入错误
base_path = os.path.dirname(
os.path.dirname(os.path.abspath(__file__))
)
sys.path.append(base_path)
#首先调用生成用例函数
create_case_file()
#查找用例
discover = unittest.defaultTestLoader.discover(
start_dir=CASE_PATH,
pattern='*.py'
)
#执行生成测试报告
tittle = '接口测试'
time_now = time.strftime('%Y-%m-%d-%H_%M_S')
runner = BetRep(discover)
runner.report(tittle,
filename='{}_接口测试'.format(time_now),
report_dir=REPORT_PATH
)
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
lib 存放各种附加的代码文件,如加密、链接数据库、生成测试脚本等
MD5加密
import hashlib
def hash_code(pwd):
md5 = hashlib.md5() #获取md5对象
md5.update(pwd.encode('utf-8')) #将传入的pwd编码后,更新MD5的状态
return md5.hexdigest() #返回十六进制的MD5码
if __name__ == '__main__':
print(hash_code('12345'))
set_case_file.py 生成测试脚本
from setting import *
def set_res_data(res):
if res:
return res.lower().replace('":"', "=").replace('":', "=")
def create_case_file():
file_lists = os.listdir(DATA_PATH) #取出data目录下的所有文件
template_file = os.path.join(BASE_PATH,'case_template.txt')
for fList in file_lists:
if fList.endswith('.yaml') or fList.endswith('.yml'):
#测试用例文件名和yaml文件名
data_file = fList.replace('.yaml','').replace('.yml','')
#测试用例方法名
test_method_name = data_file.lower() #方法名全小写
#测试用例类名
test_class_name = test_method_name.capitalize() #首字母大写
with open(template_file,'r',encoding='utf-8') as temp:
content = temp.read()%{
'class_name' :test_class_name,
'method_name' : test_method_name,
'data_file' : data_file
}
test_case_file = 'test_{}.py'.format(data_file)
#根据模板生成测试用例文件
with open(os.path.join(CASE_PATH,test_case_file),'w',encoding='utf-8') as f:
f.write(content)
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
YAML文件
以小白接口为例,数据需替换
- #用户注册
method: post
url: http://hd215.api.okayapi.com/?s=App.User.Register
data:
app_key: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
username: xxx
password: xxx
asserlist:
- ret=200
- err_code=0
- err_msg=
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————