TBC/tests/data_space/data_space_api_helpers.py
D-Robotics cfb653c2d5 v1.0.0: Python 3.9 兼容性修复 + Dashboard E2E 入口 + 文档同步
- 15个文件添加 from __future__ import annotations 修复 Python 3.9 管道语法
- DCloudDashboard 首页新增总览分组,E2E 全量测试入口卡片
- 同步更新 README/history/测试用例文档
2026-06-25 19:32:09 +08:00

344 lines
10 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.

"""数据空间 API 辅助函数
提供空间管理和文件操作的 API 封装,供 E2E 测试和 API 测试复用。
"""
from __future__ import annotations
from tests.logger import get_logger
from tests.utils import APIClient
logger = get_logger(__name__)
# ---------------------------------------------------------------------------
# 空间操作
# ---------------------------------------------------------------------------
def api_get_spaces(api_client: APIClient) -> list[dict]:
"""获取所有空间列表"""
try:
resp = api_client.post(
"/api/cloudDiskApi/spaces/list",
json={"page": 1, "page_size": 10000},
)
return resp.json().get("data", {}).get("list", [])
except Exception as e:
logger.warning(f"[API] Failed to list spaces: {e}")
return []
def api_get_space_id(api_client: APIClient, space_name: str) -> int | None:
"""通过空间名查找空间 ID"""
spaces = api_get_spaces(api_client)
for space in spaces:
if space.get("name") == space_name:
return space.get("id")
return None
def api_create_space(
api_client: APIClient,
space_name: str,
space_type: str = "private",
is_public: bool = False,
) -> int | None:
"""通过 API 创建空间,返回空间 ID
Args:
space_type: 'private' 表示个人空间,'organization' 表示组织空间
is_public: 是否公开(组织空间可设为 True)
"""
try:
resp = api_client.post(
"/api/cloudDiskApi/spaces",
json={
"name": space_name,
"type": space_type,
"is_public": is_public,
},
)
result = resp.json()
if result.get("status") == 0:
space_id = result.get("data", {}).get("id")
logger.info(f"[API] Created space '{space_name}' id={space_id}")
return space_id
else:
logger.warning(f"[API] Create space failed: {result}")
return None
except Exception as e:
logger.warning(f"[API] create_space exception: {e}")
return None
def api_delete_space(api_client: APIClient, space_id: int) -> bool:
"""通过 API 删除空间"""
try:
resp = api_client.delete(f"/api/cloudDiskApi/spaces/{space_id}")
result = resp.json()
ok = result.get("status") == 0
if ok:
logger.info(f"[API] Deleted space={space_id}")
else:
logger.warning(f"[API] Delete space failed: {result}")
return ok
except Exception as e:
logger.warning(f"[API] delete_space exception: {e}")
return False
# ---------------------------------------------------------------------------
# 文件/文件夹操作
# ---------------------------------------------------------------------------
def api_list_files(
api_client: APIClient,
space_id: int,
path: str = "",
) -> list[dict]:
"""获取指定目录下的文件列表"""
try:
resp = api_client.post(
f"/api/cloudDiskApi/files/{space_id}",
json={"path": path, "keyword": "", "page": 1, "page_size": 1000},
)
data = resp.json().get("data") or {}
files = data.get("files") or data.get("list") or []
logger.info(
f"[API] list_files path='{path}' space={space_id} count={len(files)}"
)
return files
except Exception as e:
logger.warning(f"[API] list_files exception: {e}")
return []
def api_file_exists(
api_client: APIClient, space_id: int, name: str, path: str = ""
) -> bool:
"""检查文件/文件夹是否存在"""
files = api_list_files(api_client, space_id, path)
return any(f.get("name") == name for f in files)
def api_upload_file(
api_client: APIClient,
space_id: int,
file_name: str,
content: str = "test content",
remote_path: str = "",
) -> bool:
"""上传文件到指定空间的指定目录"""
try:
resp = api_client.upload_form(
f"/api/cloudDiskApi/files/{space_id}/upload",
file_name=file_name,
file_bytes=content.encode("utf-8"),
form_data={"path": remote_path},
)
result = resp.json()
ok = result.get("status") == 0
if ok:
logger.info(
f"[API] Uploaded '{file_name}' to space={space_id} path='{remote_path}'"
)
else:
logger.warning(f"[API] Upload failed: {result}")
return ok
except Exception as e:
logger.warning(f"[API] upload_file exception: {e}")
return False
def api_delete_file(
api_client: APIClient,
space_id: int,
name: str,
is_dir: bool = False,
parent_path: str = "",
) -> bool:
"""删除文件或文件夹(API batch-delete)"""
if not space_id or not name:
return False
try:
path = f"{parent_path}/{name}" if parent_path else f"/{name}"
resp = api_client.post(
f"/api/cloudDiskApi/files/{space_id}/batch-delete",
json={"paths": [path], "is_dir": is_dir},
)
result = resp.json()
ok = result.get("status") == 0
if ok:
logger.info(
f"[API] Deleted {'dir' if is_dir else 'file'} '{path}' from space={space_id}"
)
else:
logger.warning(f"[API] Delete failed for '{path}': {result}")
return ok
except Exception as e:
logger.warning(f"[API] delete_file exception: {e}")
return False
def api_create_folder(
api_client: APIClient,
space_id: int,
folder_name: str,
parent_path: str = "",
) -> bool:
"""通过 API 创建文件夹
POST /api/cloudDiskApi/files/{space_id}/folder
Body: {name: str, path: str} # name=文件夹名, path=父目录路径
"""
try:
resp = api_client.post(
f"/api/cloudDiskApi/files/{space_id}/folder",
json={"name": folder_name, "path": parent_path},
)
result = resp.json()
ok = result.get("status") == 0
if ok:
logger.info(
f"[API] Created folder '{folder_name}' in space={space_id} parent='{parent_path}'"
)
else:
logger.warning(f"[API] Create folder failed: {result}")
return ok
except Exception as e:
logger.warning(f"[API] create_folder exception: {e}")
return False
def api_rename_file(
api_client: APIClient,
space_id: int,
old_name: str,
new_name: str,
is_dir: bool = False,
parent_path: str = "",
) -> bool:
"""重命名文件或文件夹
PUT /api/cloudDiskApi/files/{space_id}/rename
Body: {path: str, new_name: str, is_dir: bool}
"""
try:
path = f"{parent_path}/{old_name}" if parent_path else f"/{old_name}"
resp = api_client.put(
f"/api/cloudDiskApi/files/{space_id}/rename",
json={"path": path, "new_name": new_name, "is_dir": is_dir},
)
result = resp.json()
ok = result.get("status") == 0
if ok:
logger.info(
f"[API] Renamed '{old_name}' -> '{new_name}' in space={space_id}"
)
else:
logger.warning(f"[API] Rename failed: {result}")
return ok
except Exception as e:
logger.warning(f"[API] rename_file exception: {e}")
return False
def api_move_file(
api_client: APIClient,
space_id: int,
file_name: str,
target_dir: str,
dst_space_id: int | None = None,
is_dir: bool = False,
) -> bool:
"""移动文件到目标目录
PUT /api/cloudDiskApi/files/{space_id}/move
Body: {src_path, dst_path, dst_space, is_dir}
注意: dst_path 是目标目录路径(不含文件名),服务端自动保留文件名
"""
try:
src = f"/{file_name}"
dst = target_dir # 目标目录,服务端会保留 src 文件名
resp = api_client.put(
f"/api/cloudDiskApi/files/{space_id}/move",
json={
"src_path": src,
"dst_path": dst,
"dst_space": dst_space_id or space_id,
"is_dir": is_dir,
},
)
result = resp.json()
ok = result.get("status") == 0
if ok:
logger.info(f"[API] Moved '{src}' -> dir '{dst}' space={space_id}")
else:
logger.warning(f"[API] Move failed: {result}")
return ok
except Exception as e:
logger.warning(f"[API] move_file exception: {e}")
return False
def api_get_invite_code(
api_client: APIClient,
space_id: int,
invite_ttl: int = 24,
) -> str | None:
"""通过 API 生成并获取邀请码
POST /api/cloudDiskApi/spaces/{space_id}/invite
Body: {invite_ttl: int} # 过期时间(小时)
Returns: 邀请码字符串,失败返回 None
"""
try:
resp = api_client.post(
f"/api/cloudDiskApi/spaces/{space_id}/invite",
json={"invite_ttl": invite_ttl},
)
result = resp.json()
if result.get("status") == 0:
code = result.get("data", {}).get("code", "")
logger.info(f"[API] Got invite code for space={space_id}: {code}")
return code
else:
logger.warning(f"[API] Get invite code failed: {result}")
return None
except Exception as e:
logger.warning(f"[API] get_invite_code exception: {e}")
return None
# ---------------------------------------------------------------------------
# 空间查询辅助函数(供 test_data_space_api.py、test_data_space_api_boundary.py、test_data_space_flow.py 复用)
# ---------------------------------------------------------------------------
def api_get_first_space_id(api_client: APIClient) -> int | None:
"""获取第一个可用空间 ID(通用辅助函数)
从空间列表中获取第一个空间,用于测试场景中只需要任意空间的情况。
"""
spaces = api_get_spaces(api_client)
if not spaces:
return None
return spaces[0].get("id")
def api_get_personal_space_id(api_client: APIClient) -> int | None:
"""获取第一个个人空间 ID(通用辅助函数)
优先查找 type == 'private' 的空间,
如果没有个人空间,则返回第一个可用空间。
"""
spaces = api_get_spaces(api_client)
# 优先找个人空间
for space in spaces:
if space.get("type") == "private":
return space.get("id")
# 没有个人空间则返回第一个
return spaces[0].get("id") if spaces else None