在接口自动化测试中使用全局变量的多种方案及与报告工具的结合
在接口自动化测试中,处理接口依赖的全局变量有多种方案,我可以结合您现有的ReportUtils类,为您提供几种实现方式。
1. 使用全局字典管理依赖数据
创建一个全局变量类,用于存储和获取依赖数据(如 token、用户 ID 等)。
# utils/global_vars.py
class GlobalVars:
_data = {} # 存储全局变量的字典
@classmethod
def set(cls, key, value):
cls._data[key] = value
@classmethod
def get(cls, key, default=None):
return cls._data.get(key, default)
2. 在测试框架中集成全局变量
在测试前设置全局变量,测试过程中获取使用。
# conftest.py (pytest配置文件)
import pytest
from utils.global_vars import GlobalVars
@pytest.fixture(scope=\"session\", autouse=True)
def setup_global_vars():
# 在测试会话开始前初始化全局变量
# 例如:登录获取token并存入全局变量
token = login_and_get_token() # 自定义登录函数
GlobalVars.set(\"auth_token\", token)
yield # 测试结束后可以添加清理操作
3. 在 API 请求中使用全局变量
在发送请求时自动获取全局变量(如 token)。
# utils/api_client.py
import requests
from utils.global_vars import GlobalVars
class APIClient:
def __init__(self, base_url):
self.base_url = base_url
def request(self, method, endpoint, **kwargs):
# 自动添加认证头
token = GlobalVars.get(\"auth_token\")
headers = kwargs.pop(\"headers\", {})
if token:
headers[\"Authorization\"] = f\"Bearer {token}\"
url = f\"{self.base_url}{endpoint}\"
response = requests.request(method, url, headers=headers, **kwargs)
return response
def get(self, endpoint, **kwargs):
return self.request(\"GET\", endpoint, **kwargs)
def post(self, endpoint, **kwargs):
return self.request(\"POST\", endpoint, **kwargs)
4. 在测试用例中使用依赖数据
测试用例可以直接获取全局变量,或通过依赖注入获取。
# test_cases/test_user.py
from utils.api_client import APIClient
from utils.global_vars import GlobalVars
def test_create_user():
client = APIClient(\"https://api.example.com\")
payload = {\"name\": \"test_user\"}
response = client.post(\"/users\", json=payload)
assert response.status_code == 201
# 保存新创建的用户ID到全局变量
user_id = response.json()[\"id\"]
GlobalVars.set(\"current_user_id\", user_id)
def test_get_user_details():
client = APIClient(\"https://api.example.com\")
user_id = GlobalVars.get(\"current_user_id\")
response = client.get(f\"/users/{user_id}\")
assert response.status_code == 200
5. 复杂依赖场景的处理
对于需要多个依赖的场景,可以创建依赖管理器。
# utils/dependency_manager.py
from utils.api_client import APIClient
from utils.global_vars import GlobalVars
class DependencyManager:
def __init__(self):
self.client = APIClient(\"https://api.example.com\")
def get_token(self):
\"\"\"获取或刷新token\"\"\"
token = GlobalVars.get(\"auth_token\")
if not token:
# 登录获取token
response = self.client.post(\"/auth/login\", json={
\"username\": \"test\",
\"password\": \"test\"
})
token = response.json()[\"token\"]
GlobalVars.set(\"auth_token\", token)
return token
def create_test_user(self):
\"\"\"创建测试用户并返回用户ID\"\"\"
user_id = GlobalVars.get(\"test_user_id\")
if not user_id:
response = self.client.post(\"/users\", json={\"name\": \"test\"})
user_id = response.json()[\"id\"]
GlobalVars.set(\"test_user_id\", user_id)
return user_id
使用建议
- 单例模式:GlobalVars类使用类属性确保全局唯一性。
- 作用域控制:
- 使用pytest fixture的scope参数控制变量生命周期(如session、module)。
- 线程安全:
- 若并行执行测试,可使用线程安全的字典(如threading.Lock)。
- 清理机制:
- 在测试结束后(teardown)清理或重置全局变量。
结合您的报告工具
可以扩展ReportUtils类,在报告中包含全局变量状态:
# utils/report_utils.py
class ReportUtils:
@staticmethod
def generate_test_report(results, output_dir=\"reports\"):
# ... 原有代码 ...
# 添加全局变量状态到报告
from utils.global_vars import GlobalVars
report_data[\"global_vars\"] = GlobalVars._data # 仅用于演示,实际应使用get方法
# ... 原有代码 ...
这样可以在测试报告中查看全局变量的最终状态,便于问题排查。