接下来就是鉴权接口的测试。
先封装httpx的发送发送请求:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 小橙子的爸比 (279453094@qq.com)
# @Version : 1.0
# @Update Time : 2025/1/3 下午5:59
# @File : httpx_request.py
# @IDE : PyCharm
# @Desc : 文件描述信息
import httpx
from config.env_config import EnvInfo
from db.database_factory import DatabaseFactory
from utils.nb_logger import httpx_log as log
def get_sotre_token():
rds = DatabaseFactory().get_db_instance("redis").db_getter()
redis_key = EnvInfo.USER_NAME + "-" + EnvInfo.TEST_ENV_TAG + "-" + EnvInfo.REDIS_STORE_TOKEN_KEY
token = rds.get(redis_key)
if not token:
raise ValueError("token不存在")
return token
class HttpxRequest:
def __init__(self, token=get_sotre_token()):
auth_token = {"Authorization": f"Bearer {token}"}
self.headers = EnvInfo().stitching_headers(update_data=auth_token)
self.client = httpx.Client(headers=self.headers)
def get(self, uri, pargrams=None):
"""封装get请求"""
url = EnvInfo().stitching_url(uri)
resp = self.client.get(url, params=pargrams)
self.client.close()
return resp
def post(self, uri, data=None, files_path=None, file_name=None):
"""封装post请求
:files_path :上传文件的绝对路径
:file_name :上传文件的文件名
"""
files = None
url = EnvInfo().stitching_url(uri)
if files_path is not None:
files = {'upload-file': (files_path, open(file_name, 'rb'), 'application/vnd.ms-excel')}
with self.client as client:
resp = self.client.post(url, headers=self.headers, json=data, files=files)
log.info(f"POST请求:{url}")
# log.info(f"POST请求头消息:{self.headers}")
log.info(f"POST请求参数:{data}")
log.info(f"POST响应参数:{resp.text}")
return resp
需要鉴权的接口,头消息需要有"Authorization",由session级的fixture负责存入redis,这里直接由函数get_sotre_token去获取,获取不到就抛出异常。然后我们看下具体的鉴权接口的用例。还是通过@pytest.mark.abnormity,@pytest.mark.smock两个标签来区分冒烟用例和异常场景用例,数据驱动由yaml文件提供。
使用的标签需要再pytest.ini里配置:
[pytest]
;addopts = --alluredir ./allure-results --capture=no --tb=long
addopts = --alluredir ./allure-results --cache-clear --capture=no --tb=long
markers =
smock: basic case tag
abnormity: request data usally has some mistake
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 小橙子的爸比 (279453094@qq.com)
# @Version : 1.0
# @Update Time : 2025/1/4 下午7:42
# @File : test_enterprise.py
# @IDE : PyCharm
# @Desc : 文件描述信息
import os
import allure
import pytest
from config.env_config import TestDataYamlFileName, ApiUri, TableName
from project_config import settings
from utils.tools import YamlTool
from utils.httpx_request import HttpxRequest
from utils.smarthub_crud import SmarthubCRUD
yml = YamlTool(os.path.join(settings.system.DATA_PATH, TestDataYamlFileName.ENTERPRISE_YML))
print(os.path.join(settings.system.DATA_PATH, TestDataYamlFileName.ENTERPRISE_YML))
test_datas = yml.read_yaml()
@allure.feature("SMARTHUB接口测试")
@allure.story("企业接口测试")
@allure.testcase("正确参数可以创建企业")
@pytest.mark.smock
@pytest.mark.parametrize("enterprise_info", test_datas['enterprise_create']['enterprise_info'])
def test_add_enterprise(enterprise_info):
# 动态标题
allure.dynamic.title(enterprise_info['title'])
resp = HttpxRequest().post(uri=ApiUri.ENTERPRISE_URI, data=enterprise_info['data'])
assert resp.status_code == 201
# 创建数据接口,增加数据库入库检查
v_where = f"where name='{enterprise_info['data']['name']}'"
sql = SmarthubCRUD.make_sql(table_name=TableName.ENTERPRISE,v_where=v_where)
query_res = SmarthubCRUD().execute_smarthub_qurry_sql(sql)
assert len(query_res) > 0, f"新增企业数据未入库,企业名称:{enterprise_info['data']['name']}"
assert resp.status_code == 201
@allure.feature("SMARTHUB接口测试")
@allure.story("企业接口测试")
@allure.testcase("错误参数,无法创建企业")
@pytest.mark.abnormity
@pytest.mark.parametrize("enterprise_info", test_datas['enterprise_create']['enterprise_info_error'])
def test_add_enterprise_error(enterprise_info):
# 动态标题
allure.dynamic.title(enterprise_info['title'])
resp = HttpxRequest().post(uri=ApiUri.ENTERPRISE_URI, data=enterprise_info['data'])
assert resp.status_code == 422
# 创建数据接口,增加数据库入库检查
v_where = f"where name='{enterprise_info['data']['name']}'"
sql = SmarthubCRUD.make_sql(table_name=TableName.ENTERPRISE,v_where=v_where)
query_res = SmarthubCRUD().execute_smarthub_qurry_sql(sql)
assert len(query_res) > 0, f"新增企业数据(异常数据)入库,企业名称:{enterprise_info['data']['name']}"
现在就要考虑用例的后置脚本了,很烦哟。按理说,自动化测试用例要求独立性,但是后置脚本我没法完全从数据纬度去恢复测试环境,关联表太多,从数据库去恢复测试数据状态不现实(对我来说),备份数据库也是一个方法,将预置测试数据都造好后就将数据库备份起来,然后清理redis里的缓存。每次测试前就先恢复一次数据库。但是我的测试对象,每张卡跨月会自动续订套餐,备份数据库的方式就会导致数据缺失。目前我暂时通过一些接口去恢复数据。头疼!!!
576

被折叠的 条评论
为什么被折叠?



