TBC/tests/fixtures/cleanup.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

102 lines
3.2 KiB
Python
Raw Permalink 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.

"""公共 cleanup fixture 工厂
提供可复用的资源自动清理机制,消除各模块 conftest.py 中的重复 cleanup fixture 代码。
使用方法:
from tests.fixtures.cleanup import create_cleanup_fixture
# 在 conftest.py 中创建模块专属的 cleanup fixture
cleanup_tasks = create_cleanup_fixture(api_delete_task, "任务")
cleanup_workflows = create_cleanup_fixture(api_delete_workflow, "工作流")
"""
import pytest
from typing import Callable
from tests.logger import get_logger
logger = get_logger(__name__)
def create_cleanup_fixture(
delete_func: Callable, resource_name: str, scope: str = "function"
):
"""创建自动清理 fixture 的工厂函数
Args:
delete_func: 删除资源的 API 函数,签名为 (api_client, resource_id) -> bool
resource_name: 资源名称(用于日志),如 "任务"、"工作流"、"空间"
scope: fixture 作用域,默认 "function"
Returns:
pytest fixture 函数
Example:
# 在 conftest.py 中
from tests.fixtures.cleanup import create_cleanup_fixture
from tests.mymodule.api_helpers import api_delete_task
cleanup_tasks = create_cleanup_fixture(api_delete_task, "任务")
# 在测试中使用
def test_example(api_client, cleanup_tasks):
task_id = create_task(...)
cleanup_tasks.append(task_id) # 测试结束后自动清理
"""
@pytest.fixture(scope=scope)
def cleanup_fixture(api_client):
created_ids = []
yield created_ids
# 清理所有记录的资源
for resource_id in created_ids:
try:
if delete_func(api_client, resource_id):
logger.info(f"清理{resource_name}成功: {resource_id}")
else:
logger.warning(f"清理{resource_name}失败: {resource_id}")
except Exception as e:
logger.error(f"清理{resource_name}异常: {resource_id} - {e}")
return cleanup_fixture
def create_cleanup_fixture_with_extra_params(
delete_func: Callable, resource_name: str, scope: str = "function"
):
"""创建支持额外参数的自动清理 fixture
用于删除操作需要额外参数的场景(如文件删除需要 space_id)。
Args:
delete_func: 删除资源的 API 函数
resource_name: 资源名称
scope: fixture 作用域
Returns:
pytest fixture 函数
Example:
# 在测试中使用
def test_example(cleanup_files):
cleanup_files.append(("file_name", space_id)) # 元组形式
"""
@pytest.fixture(scope=scope)
def cleanup_fixture(api_client):
created_items = []
yield created_items
for item in created_items:
try:
if isinstance(item, tuple):
# 元组形式:(resource_id, *extra_params)
delete_func(api_client, *item)
else:
delete_func(api_client, item)
logger.info(f"清理{resource_name}成功: {item}")
except Exception as e:
logger.error(f"清理{resource_name}异常: {item} - {e}")
return cleanup_fixture