TBC/tests/fixtures/cleanup.py
jiawei.chen 6f6053ff51 feat: TestAgent 智能测试平台 v1.0
- CLI + Web 双平台,基于 LLM 的 TDD+DDD 自动化测试生成
- 集成 unified-test-platform 903 个 D-Cloud 用例 + 13 个 Robogo 场景
- Agent 5 步流水线: 扫描 -> DDD -> LLM 生成测试
- 精确回归 + UI 变更检查
- 可视化 HTML 测试报告
- 暗色/亮色主题切换
- 19 个 API 端点 + 6 个 SPA 页面
- 15/15 项 TDD+DDD 合规
2026-07-08 11:27:38 +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