TBC/tests/data/managers.py
d-robotics 633a797226 AutoFlow v2.0: 合并 Test (Robogo) + data-loop-automation (D-Cloud) 为统一平台
- 16 个业务模块,856 个测试用例,40 个 E2E 测试
- 单一 React 19 前端 + PlatformSwitcher 二合一切换
- Flask 后端支持 scenario/dcloud_module/dcloud_e2e/dcloud_all 四种任务类型
- E2E 测试面板:API 全链路(8条) + UI 点击(3条) + 分步测试(3个)
- SSE 实时日志流 + 飞书告警 + 定时调度
- 完整还原原 ToB 平台 TestPanel E2E 模块
2026-06-23 11:48:29 +08:00

203 lines
6.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
测试数据管理器
提供测试数据的生命周期管理,包括:
- 数据注册与跟踪
- 自动清理机制
- 测试隔离支持
使用示例:
# 在测试中使用
def test_create_dataset(api_client, data_manager):
# 创建数据
dataset = DatasetFactory.create()
response = api_client.post("/datasets", json=dataset)
dataset_id = response.json()["id"]
# 注册清理
data_manager.register(
resource_id=dataset_id,
cleanup_func=lambda id: api_client.delete(f"/datasets/{id}")
)
# 测试断言...
# 测试结束后自动清理
"""
import pytest
from typing import Callable, List, Dict, Any, Optional
from tests.logger import get_logger
_logger = get_logger("DATA_MANAGER")
class DataManager:
"""数据管理器
管理测试数据的生命周期,确保测试结束后自动清理资源。
特性:
- 支持多种资源类型
- 自动清理机制
- 错误容忍(清理失败不影响测试结果)
"""
def __init__(self):
"""初始化数据管理器"""
self._resources: List[Dict[str, Any]] = []
self._logger = _logger
def register(
self,
resource_id: str,
cleanup_func: Callable[[str], None],
resource_type: str = "unknown",
metadata: Optional[Dict[str, Any]] = None
) -> None:
"""注册需要清理的资源
Args:
resource_id: 资源ID
cleanup_func: 清理函数,接收 resource_id 作为参数
resource_type: 资源类型(用于日志)
metadata: 额外元数据
"""
self._resources.append({
"id": resource_id,
"cleanup_func": cleanup_func,
"type": resource_type,
"metadata": metadata or {}
})
self._logger.debug(f"[注册资源] {resource_type}: {resource_id}")
def cleanup(self) -> None:
"""清理所有已注册的资源
按注册的逆序清理,确保依赖关系正确处理。
清理失败会记录日志,但不会抛出异常。
"""
# 逆序清理
for resource in reversed(self._resources):
try:
resource["cleanup_func"](resource["id"])
self._logger.debug(
f"[清理成功] {resource['type']}: {resource['id']}"
)
except Exception as e:
self._logger.warning(
f"[清理失败] {resource['type']}: {resource['id']}, 错误: {e}"
)
# 清空资源列表
self._resources.clear()
def get_resources(self, resource_type: Optional[str] = None) -> List[Dict[str, Any]]:
"""获取已注册的资源列表
Args:
resource_type: 资源类型过滤(可选)
Returns:
List[Dict[str, Any]]: 资源列表
"""
if resource_type:
return [r for r in self._resources if r["type"] == resource_type]
return self._resources.copy()
def count(self, resource_type: Optional[str] = None) -> int:
"""获取资源数量
Args:
resource_type: 资源类型过滤(可选)
Returns:
int: 资源数量
"""
return len(self.get_resources(resource_type))
# ---------------------------------------------------------------------------
# Pytest Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def data_manager():
"""数据管理器 Fixture
为每个测试创建独立的数据管理器实例,测试结束后自动清理。
Yields:
DataManager: 数据管理器实例
"""
manager = DataManager()
yield manager
manager.cleanup()
def create_cleanup_fixture(
cleanup_func: Callable[[str], None],
resource_type: str = "resource"
):
"""创建特定类型的清理 fixture 工厂函数
用于为特定资源类型创建专用的清理 fixture。
Args:
cleanup_func: 清理函数
resource_type: 资源类型名称
Returns:
pytest.fixture: 清理 fixture
使用示例:
# 在 conftest.py 中
from tests.data.managers import create_cleanup_fixture
from tests.dataset.api_helpers import delete_dataset
cleanup_datasets = create_cleanup_fixture(delete_dataset, "数据集")
# 在测试中使用
def test_create_dataset(api_client, cleanup_datasets):
dataset_id = create_dataset(...)
cleanup_datasets.append(dataset_id)
"""
@pytest.fixture
def cleanup_fixture():
resource_ids: List[str] = []
yield resource_ids
# 清理所有资源
for rid in reversed(resource_ids):
try:
cleanup_func(rid)
_logger.debug(f"[清理成功] {resource_type}: {rid}")
except Exception as e:
_logger.warning(f"[清理失败] {resource_type}: {rid}, 错误: {e}")
return cleanup_fixture
# ---------------------------------------------------------------------------
# 辅助函数
# ---------------------------------------------------------------------------
def create_cleanup_func(api_client, endpoint: str) -> Callable[[str], None]:
"""创建 API 清理函数
工厂函数,用于创建调用 API 删除资源的清理函数。
Args:
api_client: API 客户端
endpoint: API 端点(如 "/datasets")
Returns:
Callable[[str], None]: 清理函数
使用示例:
cleanup_dataset = create_cleanup_func(api_client, "/datasets")
cleanup_dataset(dataset_id)
"""
def cleanup(resource_id: str) -> None:
api_client.delete(f"{endpoint}/{resource_id}")
return cleanup