项目结构
project:api_test
——api_keyword
————api_key.py:接口关键字驱动类
——case
————test_cases.py:测试套件和测试用例
——report_allure(无需创建):allure报告
——result(无需创建):测试用例运行结果
——VAR
————VAR.py:常量类
conftest.py:项目级别fixture
main.py:主函数
1. api_key.py
getattr和eval在接口测试中的应用场景,封装一个接口关键字驱动类ApiKey,作为一个基类,是整个框架的核心,用于提供自动化接口测试的关键字方法。
- 各种模拟请求方法:post/get/put/delete/header/…
- 集成Allure时,可添加@allure.step,这样在自动化执行的时候 allure报告可以直接捕捉相关的执行信息,让测试报告信息更详细
- 进行断言封装
代码实现
import json
import allure
import jsonpath
import requests
import pymysql
import hashlib
import time
from Crypto.Cipher import AES
import base64
import rsa
class ApiKey:
# get请求的封装:因为params可能存在无值的情况,存放默认None
@allure.step("发送get请求")
def get(self, url, params=None, **kwargs):
return requests.get(url=url, params=params, **kwargs)
@allure.step("发送post请求")
# post请求的封装:data也可能存在无值得情况,存放默认None
def post(self, url, data=None, **kwargs):
return requests.post(url=url, data=data, **kwargs)
@allure.step("获取返回结果字典值")
# 基于jsonpath获取数据的关键字:用于提取所需要的内容
def get_text(self, data, key):
# jsonpath获取数据的表达式:成功则返回list,失败则返回false
# loads是将json格式的内容转换为字典的格式
# jsonpath接收的是dict类型的数据
dict_data = json.loads(data)
value = jsonpath.jsonpath(dict_data, key)
if isinstance(value, list):
return value[0]
else:
return value
@allure.step("断言实际结果等于预期结果")
def my_assert(self, acutal, expect):
try:
assert acutal == expect
except:
return "断言失败"
else:
return "断言成功"
# 数据库检查
@allure.step("数据库检查参数")
def sqlCheck(self, sql, n):
conn = pymysql.connect(
host='shop-xo.hctestedu.com',
port=3306,
user='api_test',
passwd='Aa9999!',
database='shopxo_hctested',
charset='utf8')
# 创建游标
cmd = conn.cursor()
# 准备并执行sql语句
cmd.execute(query=sql)
# 获取n条查询结果
results = cmd.fetchmany(n)[0][0]
conn.close()
return results
@allure.step("Md5加密")
def enMd5(self, text):
# 获取变量的内存地址,获取加密后的密文值
return hashlib.md5(text.encode('utf-8')).hexdigest()
# AES加密填充使用
def pad(self, text):
"""
#填充函数,使被加密数据的字节码长度是block_size的整数倍
"""
length = AES.block_size # 初始化数据块大小
count = len(text.encode('utf-8'))
add = length - (count % length)
entext = text + (chr(add) * add)
return entext
@allure.step("AES加密")
def enAES(self, key, text):
global aes
key = key.encode("utf-8") # 初始化密钥
aes = AES.new(key, AES.MODE_ECB) # 初始化AES,ECB模式的实例,可以选择其他模式
res = aes.encrypt(self.pad(text).encode("utf8"))
# Base64是网络上最常见的用于传输8Bit字节码的编码方式之一
msg = str(base64.b64encode(res), encoding="utf8"