fix: auto-fix code issues (cron)
- 修复重复导入/字段 - 修复异常处理 - 修复PEP8格式问题 - 修复语法错误(运算符空格问题) - 修复类型注解格式
This commit is contained in:
@@ -225,3 +225,7 @@
|
||||
- 第 541 行: line_too_long
|
||||
- 第 579 行: line_too_long
|
||||
- ... 还有 2 个类似问题
|
||||
|
||||
## Git 提交结果
|
||||
|
||||
✅ 提交并推送成功
|
||||
|
||||
BIN
__pycache__/auto_code_fixer.cpython-312.pyc
Normal file
BIN
__pycache__/auto_code_fixer.cpython-312.pyc
Normal file
Binary file not shown.
BIN
__pycache__/auto_fix_code.cpython-312.pyc
Normal file
BIN
__pycache__/auto_fix_code.cpython-312.pyc
Normal file
Binary file not shown.
BIN
__pycache__/code_review_fixer.cpython-312.pyc
Normal file
BIN
__pycache__/code_review_fixer.cpython-312.pyc
Normal file
Binary file not shown.
BIN
__pycache__/code_reviewer.cpython-312.pyc
Normal file
BIN
__pycache__/code_reviewer.cpython-312.pyc
Normal file
Binary file not shown.
@@ -21,7 +21,7 @@ class CodeIssue:
|
||||
message: str,
|
||||
severity: str = "warning",
|
||||
original_line: str = "",
|
||||
):
|
||||
) -> None:
|
||||
self.file_path = file_path
|
||||
self.line_no = line_no
|
||||
self.issue_type = issue_type
|
||||
@@ -30,14 +30,14 @@ class CodeIssue:
|
||||
self.original_line = original_line
|
||||
self.fixed = False
|
||||
|
||||
def __repr__(self):
|
||||
def __repr__(self) -> None:
|
||||
return f"{self.file_path}:{self.line_no} [{self.severity}] {self.issue_type}: {self.message}"
|
||||
|
||||
|
||||
class CodeFixer:
|
||||
"""代码自动修复器"""
|
||||
|
||||
def __init__(self, project_path: str):
|
||||
def __init__(self, project_path: str) -> None:
|
||||
self.project_path = Path(project_path)
|
||||
self.issues: list[CodeIssue] = []
|
||||
self.fixed_issues: list[CodeIssue] = []
|
||||
@@ -85,7 +85,7 @@ class CodeFixer:
|
||||
) -> None:
|
||||
"""检查裸异常捕获"""
|
||||
for i, line in enumerate(lines, 1):
|
||||
# 匹配 except: 但不匹配 except Exception: 或 except SpecificError:
|
||||
# 匹配 except Exception: 但不匹配 except Exception: 或 except SpecificError:
|
||||
if re.search(r"except\s*:\s*$", line) or re.search(r"except\s*:\s*#", line):
|
||||
# 跳过注释说明的情况
|
||||
if "# noqa" in line or "# intentional" in line.lower():
|
||||
@@ -301,9 +301,9 @@ class CodeFixer:
|
||||
line_idx = issue.line_no - 1
|
||||
if 0 <= line_idx < len(lines) and line_idx not in fixed_lines:
|
||||
line = lines[line_idx]
|
||||
# 将 except: 改为 except Exception:
|
||||
# 将 except Exception: 改为 except Exception:
|
||||
if re.search(r"except\s*:\s*$", line.strip()):
|
||||
lines[line_idx] = line.replace("except:", "except Exception:")
|
||||
lines[line_idx] = line.replace("except Exception:", "except Exception:")
|
||||
fixed_lines.add(line_idx)
|
||||
issue.fixed = True
|
||||
self.fixed_issues.append(issue)
|
||||
@@ -459,7 +459,7 @@ def git_commit_and_push(project_path: str) -> tuple[bool, str]:
|
||||
return False, f"Git 操作异常: {e}"
|
||||
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
project_path = "/root/.openclaw/workspace/projects/insightflow"
|
||||
|
||||
print("🔍 开始扫描代码...")
|
||||
|
||||
@@ -29,7 +29,7 @@ def run_ruff_check(directory: str) -> list[dict]:
|
||||
|
||||
|
||||
def fix_bare_except(content: str) -> str:
|
||||
"""修复裸异常捕获 - 将 bare except: 改为 except Exception:"""
|
||||
"""修复裸异常捕获 - 将 bare except Exception: 改为 except Exception:"""
|
||||
pattern = r'except\s*:\s*\n'
|
||||
replacement = 'except Exception:\n'
|
||||
return re.sub(pattern, replacement, content)
|
||||
@@ -104,7 +104,7 @@ def fix_file(filepath: str, issues: list[dict]) -> tuple[bool, list[str], list[s
|
||||
return False, fixed_issues, manual_fix_needed
|
||||
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
base_dir = Path("/root/.openclaw/workspace/projects/insightflow")
|
||||
backend_dir = base_dir / "backend"
|
||||
|
||||
|
||||
BIN
backend/__pycache__/ai_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/ai_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/api_key_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/api_key_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/collaboration_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/collaboration_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/db_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/db_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/developer_ecosystem_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/developer_ecosystem_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/document_processor.cpython-312.pyc
Normal file
BIN
backend/__pycache__/document_processor.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/enterprise_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/enterprise_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/entity_aligner.cpython-312.pyc
Normal file
BIN
backend/__pycache__/entity_aligner.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/export_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/export_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/growth_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/growth_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/image_processor.cpython-312.pyc
Normal file
BIN
backend/__pycache__/image_processor.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/init_db.cpython-312.pyc
Normal file
BIN
backend/__pycache__/init_db.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/knowledge_reasoner.cpython-312.pyc
Normal file
BIN
backend/__pycache__/knowledge_reasoner.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/llm_client.cpython-312.pyc
Normal file
BIN
backend/__pycache__/llm_client.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/localization_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/localization_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/main.cpython-312.pyc
Normal file
BIN
backend/__pycache__/main.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/multimodal_entity_linker.cpython-312.pyc
Normal file
BIN
backend/__pycache__/multimodal_entity_linker.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/multimodal_processor.cpython-312.pyc
Normal file
BIN
backend/__pycache__/multimodal_processor.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/neo4j_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/neo4j_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/ops_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/ops_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/oss_uploader.cpython-312.pyc
Normal file
BIN
backend/__pycache__/oss_uploader.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/performance_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/performance_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/plugin_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/plugin_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/rate_limiter.cpython-312.pyc
Normal file
BIN
backend/__pycache__/rate_limiter.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/search_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/search_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/security_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/security_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/subscription_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/subscription_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/tenant_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/tenant_manager.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/test_multimodal.cpython-312.pyc
Normal file
BIN
backend/__pycache__/test_multimodal.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/test_phase7_task6_8.cpython-312.pyc
Normal file
BIN
backend/__pycache__/test_phase7_task6_8.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/test_phase8_task1.cpython-312.pyc
Normal file
BIN
backend/__pycache__/test_phase8_task1.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/test_phase8_task2.cpython-312.pyc
Normal file
BIN
backend/__pycache__/test_phase8_task2.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/test_phase8_task4.cpython-312.pyc
Normal file
BIN
backend/__pycache__/test_phase8_task4.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/test_phase8_task5.cpython-312.pyc
Normal file
BIN
backend/__pycache__/test_phase8_task5.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/test_phase8_task6.cpython-312.pyc
Normal file
BIN
backend/__pycache__/test_phase8_task6.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/test_phase8_task8.cpython-312.pyc
Normal file
BIN
backend/__pycache__/test_phase8_task8.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/tingwu_client.cpython-312.pyc
Normal file
BIN
backend/__pycache__/tingwu_client.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/__pycache__/workflow_manager.cpython-312.pyc
Normal file
BIN
backend/__pycache__/workflow_manager.cpython-312.pyc
Normal file
Binary file not shown.
@@ -370,7 +370,7 @@ class ApiKeyManager:
|
||||
ip_address: str = "",
|
||||
user_agent: str = "",
|
||||
error_message: str = "",
|
||||
):
|
||||
) -> None:
|
||||
"""记录 API 调用日志"""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.execute(
|
||||
|
||||
@@ -136,7 +136,7 @@ class TeamSpace:
|
||||
class CollaborationManager:
|
||||
"""协作管理主类"""
|
||||
|
||||
def __init__(self, db_manager=None):
|
||||
def __init__(self, db_manager = None) -> None:
|
||||
self.db = db_manager
|
||||
self._shares_cache: dict[str, ProjectShare] = {}
|
||||
self._comments_cache: dict[str, list[Comment]] = {}
|
||||
|
||||
@@ -41,7 +41,7 @@ class Entity:
|
||||
created_at: str = ""
|
||||
updated_at: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
def __post_init__(self) -> None:
|
||||
if self.aliases is None:
|
||||
self.aliases = []
|
||||
if self.attributes is None:
|
||||
@@ -64,7 +64,7 @@ class AttributeTemplate:
|
||||
created_at: str = ""
|
||||
updated_at: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
def __post_init__(self) -> None:
|
||||
if self.options is None:
|
||||
self.options = []
|
||||
|
||||
@@ -85,7 +85,7 @@ class EntityAttribute:
|
||||
created_at: str = ""
|
||||
updated_at: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
def __post_init__(self) -> None:
|
||||
if self.options is None:
|
||||
self.options = []
|
||||
|
||||
@@ -116,12 +116,12 @@ class EntityMention:
|
||||
|
||||
|
||||
class DatabaseManager:
|
||||
def __init__(self, db_path: str = DB_PATH):
|
||||
def __init__(self, db_path: str = DB_PATH) -> None:
|
||||
self.db_path = db_path
|
||||
os.makedirs(os.path.dirname(db_path), exist_ok = True)
|
||||
self.init_db()
|
||||
|
||||
def get_conn(self):
|
||||
def get_conn(self) -> None:
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
@@ -366,7 +366,7 @@ class DatabaseManager:
|
||||
filename: str,
|
||||
full_text: str,
|
||||
transcript_type: str = "audio",
|
||||
):
|
||||
) -> None:
|
||||
conn = self.get_conn()
|
||||
now = datetime.now().isoformat()
|
||||
conn.execute(
|
||||
@@ -414,7 +414,7 @@ class DatabaseManager:
|
||||
relation_type: str = "related",
|
||||
evidence: str = "",
|
||||
transcript_id: str = "",
|
||||
):
|
||||
) -> None:
|
||||
conn = self.get_conn()
|
||||
relation_id = str(uuid.uuid4())[:UUID_LENGTH]
|
||||
now = datetime.now().isoformat()
|
||||
@@ -479,7 +479,7 @@ class DatabaseManager:
|
||||
conn.close()
|
||||
return dict(row) if row else None
|
||||
|
||||
def delete_relation(self, relation_id: str):
|
||||
def delete_relation(self, relation_id: str) -> None:
|
||||
conn = self.get_conn()
|
||||
conn.execute("DELETE FROM entity_relations WHERE id = ?", (relation_id, ))
|
||||
conn.commit()
|
||||
@@ -520,7 +520,7 @@ class DatabaseManager:
|
||||
conn.close()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def delete_glossary_term(self, term_id: str):
|
||||
def delete_glossary_term(self, term_id: str) -> None:
|
||||
conn = self.get_conn()
|
||||
conn.execute("DELETE FROM glossary WHERE id = ?", (term_id, ))
|
||||
conn.commit()
|
||||
@@ -830,7 +830,7 @@ class DatabaseManager:
|
||||
conn.close()
|
||||
return self.get_attribute_template(template_id)
|
||||
|
||||
def delete_attribute_template(self, template_id: str):
|
||||
def delete_attribute_template(self, template_id: str) -> None:
|
||||
conn = self.get_conn()
|
||||
conn.execute("DELETE FROM attribute_templates WHERE id = ?", (template_id, ))
|
||||
conn.commit()
|
||||
@@ -927,7 +927,7 @@ class DatabaseManager:
|
||||
|
||||
def delete_entity_attribute(
|
||||
self, entity_id: str, template_id: str, changed_by: str = "system", change_reason: str = ""
|
||||
):
|
||||
) -> None:
|
||||
conn = self.get_conn()
|
||||
old_row = conn.execute(
|
||||
"""SELECT value FROM entity_attributes
|
||||
|
||||
@@ -348,7 +348,7 @@ class DeveloperPortalConfig:
|
||||
class DeveloperEcosystemManager:
|
||||
"""开发者生态系统管理主类"""
|
||||
|
||||
def __init__(self, db_path: str = DB_PATH):
|
||||
def __init__(self, db_path: str = DB_PATH) -> None:
|
||||
self.db_path = db_path
|
||||
self.platform_fee_rate = 0.30 # 平台抽成比例 30%
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import os
|
||||
class DocumentProcessor:
|
||||
"""文档处理器 - 提取 PDF/DOCX 文本"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.supported_formats = {
|
||||
".pdf": self._extract_pdf,
|
||||
".docx": self._extract_docx,
|
||||
|
||||
@@ -329,7 +329,7 @@ class EnterpriseManager:
|
||||
],
|
||||
}
|
||||
|
||||
def __init__(self, db_path: str = "insightflow.db"):
|
||||
def __init__(self, db_path: str = "insightflow.db") -> None:
|
||||
self.db_path = db_path
|
||||
self._init_db()
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ class EntityEmbedding:
|
||||
class EntityAligner:
|
||||
"""实体对齐器 - 使用 embedding 进行相似度匹配"""
|
||||
|
||||
def __init__(self, similarity_threshold: float = 0.85):
|
||||
def __init__(self, similarity_threshold: float = 0.85) -> None:
|
||||
self.similarity_threshold = similarity_threshold
|
||||
self.embedding_cache: dict[str, list[float]] = {}
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ class ExportTranscript:
|
||||
class ExportManager:
|
||||
"""导出管理器 - 处理各种导出需求"""
|
||||
|
||||
def __init__(self, db_manager=None):
|
||||
def __init__(self, db_manager = None) -> None:
|
||||
self.db = db_manager
|
||||
|
||||
def export_knowledge_graph_svg(
|
||||
|
||||
@@ -362,7 +362,7 @@ class TeamIncentive:
|
||||
class GrowthManager:
|
||||
"""运营与增长管理主类"""
|
||||
|
||||
def __init__(self, db_path: str = DB_PATH):
|
||||
def __init__(self, db_path: str = DB_PATH) -> None:
|
||||
self.db_path = db_path
|
||||
self.mixpanel_token = os.getenv("MIXPANEL_TOKEN", "")
|
||||
self.amplitude_api_key = os.getenv("AMPLITUDE_API_KEY", "")
|
||||
@@ -443,7 +443,7 @@ class GrowthManager:
|
||||
|
||||
return event
|
||||
|
||||
async def _send_to_analytics_platforms(self, event: AnalyticsEvent):
|
||||
async def _send_to_analytics_platforms(self, event: AnalyticsEvent) -> None:
|
||||
"""发送事件到第三方分析平台"""
|
||||
tasks = []
|
||||
|
||||
@@ -455,7 +455,7 @@ class GrowthManager:
|
||||
if tasks:
|
||||
await asyncio.gather(*tasks, return_exceptions = True)
|
||||
|
||||
async def _send_to_mixpanel(self, event: AnalyticsEvent):
|
||||
async def _send_to_mixpanel(self, event: AnalyticsEvent) -> None:
|
||||
"""发送事件到 Mixpanel"""
|
||||
try:
|
||||
headers = {
|
||||
@@ -480,7 +480,7 @@ class GrowthManager:
|
||||
except (RuntimeError, ValueError, TypeError) as e:
|
||||
print(f"Failed to send to Mixpanel: {e}")
|
||||
|
||||
async def _send_to_amplitude(self, event: AnalyticsEvent):
|
||||
async def _send_to_amplitude(self, event: AnalyticsEvent) -> None:
|
||||
"""发送事件到 Amplitude"""
|
||||
try:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
@@ -510,7 +510,7 @@ class GrowthManager:
|
||||
|
||||
async def _update_user_profile(
|
||||
self, tenant_id: str, user_id: str, event_type: EventType, event_name: str
|
||||
):
|
||||
) -> None:
|
||||
"""更新用户画像"""
|
||||
with self._get_db() as conn:
|
||||
# 检查用户画像是否存在
|
||||
@@ -1027,7 +1027,7 @@ class GrowthManager:
|
||||
user_id: str,
|
||||
metric_name: str,
|
||||
metric_value: float,
|
||||
):
|
||||
) -> None:
|
||||
"""记录实验指标"""
|
||||
with self._get_db() as conn:
|
||||
conn.execute(
|
||||
@@ -1569,7 +1569,7 @@ class GrowthManager:
|
||||
|
||||
return workflow
|
||||
|
||||
async def trigger_workflow(self, workflow_id: str, event_data: dict):
|
||||
async def trigger_workflow(self, workflow_id: str, event_data: dict) -> None:
|
||||
"""触发自动化工作流"""
|
||||
with self._get_db() as conn:
|
||||
row = conn.execute(
|
||||
@@ -1606,7 +1606,7 @@ class GrowthManager:
|
||||
return False
|
||||
return True
|
||||
|
||||
async def _execute_action(self, action: dict, event_data: dict):
|
||||
async def _execute_action(self, action: dict, event_data: dict) -> None:
|
||||
"""执行工作流动作"""
|
||||
action_type = action.get("type")
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ class InferencePath:
|
||||
class KnowledgeReasoner:
|
||||
"""知识推理引擎"""
|
||||
|
||||
def __init__(self, api_key: str = None, base_url: str = None):
|
||||
def __init__(self, api_key: str = None, base_url: str = None) -> None:
|
||||
self.api_key = api_key or KIMI_API_KEY
|
||||
self.base_url = base_url or KIMI_BASE_URL
|
||||
self.headers = {
|
||||
|
||||
@@ -41,7 +41,7 @@ class RelationExtractionResult:
|
||||
class LLMClient:
|
||||
"""Kimi API 客户端"""
|
||||
|
||||
def __init__(self, api_key: str = None, base_url: str = None):
|
||||
def __init__(self, api_key: str = None, base_url: str = None) -> None:
|
||||
self.api_key = api_key or KIMI_API_KEY
|
||||
self.base_url = base_url or KIMI_BASE_URL
|
||||
self.headers = {
|
||||
|
||||
@@ -719,7 +719,7 @@ class LocalizationManager:
|
||||
},
|
||||
}
|
||||
|
||||
def __init__(self, db_path: str = "insightflow.db"):
|
||||
def __init__(self, db_path: str = "insightflow.db") -> None:
|
||||
self.db_path = db_path
|
||||
self._is_memory_db = db_path == ":memory:"
|
||||
self._conn = None
|
||||
@@ -736,11 +736,11 @@ class LocalizationManager:
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
def _close_if_file_db(self, conn):
|
||||
def _close_if_file_db(self, conn) -> None:
|
||||
if not self._is_memory_db:
|
||||
conn.close()
|
||||
|
||||
def _init_db(self):
|
||||
def _init_db(self) -> None:
|
||||
conn = self._get_connection()
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
@@ -863,7 +863,7 @@ class LocalizationManager:
|
||||
finally:
|
||||
self._close_if_file_db(conn)
|
||||
|
||||
def _init_default_data(self):
|
||||
def _init_default_data(self) -> None:
|
||||
conn = self._get_connection()
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
|
||||
@@ -32,7 +32,7 @@ class MultimodalEntity:
|
||||
confidence: float
|
||||
modality_features: dict = None # 模态特定特征
|
||||
|
||||
def __post_init__(self):
|
||||
def __post_init__(self) -> None:
|
||||
if self.modality_features is None:
|
||||
self.modality_features = {}
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ class VideoFrame:
|
||||
ocr_confidence: float = 0.0
|
||||
entities_detected: list[dict] = None
|
||||
|
||||
def __post_init__(self):
|
||||
def __post_init__(self) -> None:
|
||||
if self.entities_detected is None:
|
||||
self.entities_detected = []
|
||||
|
||||
@@ -76,7 +76,7 @@ class VideoInfo:
|
||||
error_message: str = ""
|
||||
metadata: dict = None
|
||||
|
||||
def __post_init__(self):
|
||||
def __post_init__(self) -> None:
|
||||
if self.metadata is None:
|
||||
self.metadata = {}
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ class GraphEntity:
|
||||
aliases: list[str] = None
|
||||
properties: dict = None
|
||||
|
||||
def __post_init__(self):
|
||||
def __post_init__(self) -> None:
|
||||
if self.aliases is None:
|
||||
self.aliases = []
|
||||
if self.properties is None:
|
||||
@@ -57,7 +57,7 @@ class GraphRelation:
|
||||
evidence: str = ""
|
||||
properties: dict = None
|
||||
|
||||
def __post_init__(self):
|
||||
def __post_init__(self) -> None:
|
||||
if self.properties is None:
|
||||
self.properties = {}
|
||||
|
||||
@@ -95,7 +95,7 @@ class CentralityResult:
|
||||
class Neo4jManager:
|
||||
"""Neo4j 图数据库管理器"""
|
||||
|
||||
def __init__(self, uri: str = None, user: str = None, password: str = None):
|
||||
def __init__(self, uri: str = None, user: str = None, password: str = None) -> None:
|
||||
self.uri = uri or NEO4J_URI
|
||||
self.user = user or NEO4J_USER
|
||||
self.password = password or NEO4J_PASSWORD
|
||||
|
||||
@@ -449,7 +449,7 @@ class CostOptimizationSuggestion:
|
||||
class OpsManager:
|
||||
"""运维与监控管理主类"""
|
||||
|
||||
def __init__(self, db_path: str = DB_PATH):
|
||||
def __init__(self, db_path: str = DB_PATH) -> None:
|
||||
self.db_path = db_path
|
||||
self._alert_evaluators: dict[str, Callable] = {}
|
||||
self._running = False
|
||||
@@ -812,7 +812,7 @@ class OpsManager:
|
||||
|
||||
return False
|
||||
|
||||
async def evaluate_alert_rules(self, tenant_id: str):
|
||||
async def evaluate_alert_rules(self, tenant_id: str) -> None:
|
||||
"""评估所有告警规则"""
|
||||
rules = self.list_alert_rules(tenant_id, is_enabled = True)
|
||||
|
||||
@@ -828,7 +828,7 @@ class OpsManager:
|
||||
# 触发告警
|
||||
await self._trigger_alert(rule, metrics[-1] if metrics else None)
|
||||
|
||||
async def _trigger_alert(self, rule: AlertRule, metric: ResourceMetric | None):
|
||||
async def _trigger_alert(self, rule: AlertRule, metric: ResourceMetric | None) -> None:
|
||||
"""触发告警"""
|
||||
# 检查是否已有相同告警在触发中
|
||||
existing = self.get_active_alert_by_rule(rule.id)
|
||||
@@ -898,7 +898,7 @@ class OpsManager:
|
||||
# 发送告警通知
|
||||
await self._send_alert_notifications(alert, rule)
|
||||
|
||||
async def _send_alert_notifications(self, alert: Alert, rule: AlertRule):
|
||||
async def _send_alert_notifications(self, alert: Alert, rule: AlertRule) -> None:
|
||||
"""发送告警通知到所有配置的渠道"""
|
||||
channels = []
|
||||
for channel_id in rule.channels:
|
||||
|
||||
@@ -11,7 +11,7 @@ import oss2
|
||||
|
||||
|
||||
class OSSUploader:
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.access_key = os.getenv("ALI_ACCESS_KEY")
|
||||
self.secret_key = os.getenv("ALI_SECRET_KEY")
|
||||
self.bucket_name = os.getenv("OSS_BUCKET", "insightflow-audio")
|
||||
|
||||
@@ -164,7 +164,7 @@ class CacheManager:
|
||||
max_memory_size: int = 100 * 1024 * 1024, # 100MB
|
||||
default_ttl: int = 3600, # 1小时
|
||||
db_path: str = "insightflow.db",
|
||||
):
|
||||
) -> None:
|
||||
self.db_path = db_path
|
||||
self.default_ttl = default_ttl
|
||||
self.max_memory_size = max_memory_size
|
||||
@@ -619,7 +619,7 @@ class DatabaseSharding:
|
||||
base_db_path: str = "insightflow.db",
|
||||
shard_db_dir: str = "./shards",
|
||||
shards_count: int = 4,
|
||||
):
|
||||
) -> None:
|
||||
self.base_db_path = base_db_path
|
||||
self.shard_db_dir = shard_db_dir
|
||||
self.shards_count = shards_count
|
||||
@@ -917,7 +917,7 @@ class TaskQueue:
|
||||
- 任务状态追踪和重试机制
|
||||
"""
|
||||
|
||||
def __init__(self, redis_url: str | None = None, db_path: str = "insightflow.db"):
|
||||
def __init__(self, redis_url: str | None = None, db_path: str = "insightflow.db") -> None:
|
||||
self.db_path = db_path
|
||||
self.redis_url = redis_url
|
||||
self.celery_app = None
|
||||
@@ -1307,7 +1307,7 @@ class PerformanceMonitor:
|
||||
db_path: str = "insightflow.db",
|
||||
slow_query_threshold: int = 1000,
|
||||
alert_threshold: int = 5000, # 毫秒
|
||||
): # 毫秒
|
||||
) -> None: # 毫秒
|
||||
self.db_path = db_path
|
||||
self.slow_query_threshold = slow_query_threshold
|
||||
self.alert_threshold = alert_threshold
|
||||
@@ -1326,7 +1326,7 @@ class PerformanceMonitor:
|
||||
duration_ms: float,
|
||||
endpoint: str | None = None,
|
||||
metadata: dict | None = None,
|
||||
):
|
||||
) -> None:
|
||||
"""
|
||||
记录性能指标
|
||||
|
||||
@@ -1668,7 +1668,7 @@ def monitored(monitor: PerformanceMonitor, metric_type: str, endpoint: str | Non
|
||||
|
||||
def decorator(func: Callable) -> Callable:
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
def wrapper(*args, **kwargs) -> None:
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
@@ -1699,7 +1699,7 @@ class PerformanceManager:
|
||||
db_path: str = "insightflow.db",
|
||||
redis_url: str | None = None,
|
||||
enable_sharding: bool = False,
|
||||
):
|
||||
) -> None:
|
||||
self.db_path = db_path
|
||||
|
||||
# 初始化各模块
|
||||
|
||||
@@ -162,7 +162,7 @@ class ChromeExtensionToken:
|
||||
class PluginManager:
|
||||
"""插件管理主类"""
|
||||
|
||||
def __init__(self, db_manager=None):
|
||||
def __init__(self, db_manager = None) -> None:
|
||||
self.db = db_manager
|
||||
self._handlers = {}
|
||||
self._register_default_handlers()
|
||||
@@ -402,7 +402,7 @@ class PluginManager:
|
||||
class ChromeExtensionHandler:
|
||||
"""Chrome 扩展处理器"""
|
||||
|
||||
def __init__(self, plugin_manager: PluginManager):
|
||||
def __init__(self, plugin_manager: PluginManager) -> None:
|
||||
self.pm = plugin_manager
|
||||
|
||||
def create_token(
|
||||
@@ -606,7 +606,7 @@ class ChromeExtensionHandler:
|
||||
class BotHandler:
|
||||
"""飞书/钉钉机器人处理器"""
|
||||
|
||||
def __init__(self, plugin_manager: PluginManager, bot_type: str):
|
||||
def __init__(self, plugin_manager: PluginManager, bot_type: str) -> None:
|
||||
self.pm = plugin_manager
|
||||
self.bot_type = bot_type
|
||||
|
||||
@@ -934,7 +934,7 @@ class BotHandler:
|
||||
class WebhookIntegration:
|
||||
"""Zapier/Make Webhook 集成"""
|
||||
|
||||
def __init__(self, plugin_manager: PluginManager, endpoint_type: str):
|
||||
def __init__(self, plugin_manager: PluginManager, endpoint_type: str) -> None:
|
||||
self.pm = plugin_manager
|
||||
self.endpoint_type = endpoint_type
|
||||
|
||||
@@ -1157,7 +1157,7 @@ class WebhookIntegration:
|
||||
class WebDAVSyncManager:
|
||||
"""WebDAV 同步管理"""
|
||||
|
||||
def __init__(self, plugin_manager: PluginManager):
|
||||
def __init__(self, plugin_manager: PluginManager) -> None:
|
||||
self.pm = plugin_manager
|
||||
|
||||
def create_sync(
|
||||
|
||||
@@ -35,7 +35,7 @@ class RateLimitInfo:
|
||||
class SlidingWindowCounter:
|
||||
"""滑动窗口计数器"""
|
||||
|
||||
def __init__(self, window_size: int = 60):
|
||||
def __init__(self, window_size: int = 60) -> None:
|
||||
self.window_size = window_size
|
||||
self.requests: dict[int, int] = defaultdict(int) # 秒级计数
|
||||
self._lock = asyncio.Lock()
|
||||
@@ -184,12 +184,12 @@ def rate_limit(requests_per_minute: int = 60, key_func: Callable | None = None)
|
||||
key_func: 生成限流键的函数,默认为 None(使用函数名)
|
||||
"""
|
||||
|
||||
def decorator(func):
|
||||
def decorator(func) -> None:
|
||||
limiter = get_rate_limiter()
|
||||
config = RateLimitConfig(requests_per_minute = requests_per_minute)
|
||||
|
||||
@wraps(func)
|
||||
async def async_wrapper(*args, **kwargs):
|
||||
async def async_wrapper(*args, **kwargs) -> None:
|
||||
key = key_func(*args, **kwargs) if key_func else func.__name__
|
||||
info = await limiter.is_allowed(key, config)
|
||||
|
||||
@@ -201,7 +201,7 @@ def rate_limit(requests_per_minute: int = 60, key_func: Callable | None = None)
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
@wraps(func)
|
||||
def sync_wrapper(*args, **kwargs):
|
||||
def sync_wrapper(*args, **kwargs) -> None:
|
||||
key = key_func(*args, **kwargs) if key_func else func.__name__
|
||||
# 同步版本使用 asyncio.run
|
||||
info = asyncio.run(limiter.is_allowed(key, config))
|
||||
|
||||
@@ -189,7 +189,7 @@ class FullTextSearch:
|
||||
- 支持布尔搜索(AND/OR/NOT)
|
||||
"""
|
||||
|
||||
def __init__(self, db_path: str = "insightflow.db"):
|
||||
def __init__(self, db_path: str = "insightflow.db") -> None:
|
||||
self.db_path = db_path
|
||||
self._init_search_tables()
|
||||
|
||||
@@ -805,7 +805,7 @@ class SemanticSearch:
|
||||
self,
|
||||
db_path: str = "insightflow.db",
|
||||
model_name: str = "paraphrase-multilingual-MiniLM-L12-v2",
|
||||
):
|
||||
) -> None:
|
||||
self.db_path = db_path
|
||||
self.model_name = model_name
|
||||
self.model = None
|
||||
@@ -1165,7 +1165,7 @@ class EntityPathDiscovery:
|
||||
- 路径可视化数据生成
|
||||
"""
|
||||
|
||||
def __init__(self, db_path: str = "insightflow.db"):
|
||||
def __init__(self, db_path: str = "insightflow.db") -> None:
|
||||
self.db_path = db_path
|
||||
|
||||
def _get_conn(self) -> sqlite3.Connection:
|
||||
@@ -1278,7 +1278,7 @@ class EntityPathDiscovery:
|
||||
|
||||
paths = []
|
||||
|
||||
def dfs(current_id: str, target_id: str, path: list[str], visited: set[str], depth: int):
|
||||
def dfs(current_id: str, target_id: str, path: list[str], visited: set[str], depth: int) -> None:
|
||||
if depth > max_depth:
|
||||
return
|
||||
|
||||
@@ -1638,7 +1638,7 @@ class KnowledgeGapDetection:
|
||||
- 生成知识补全建议
|
||||
"""
|
||||
|
||||
def __init__(self, db_path: str = "insightflow.db"):
|
||||
def __init__(self, db_path: str = "insightflow.db") -> None:
|
||||
self.db_path = db_path
|
||||
|
||||
def _get_conn(self) -> sqlite3.Connection:
|
||||
@@ -2040,7 +2040,7 @@ class SearchManager:
|
||||
整合全文搜索、语义搜索、实体路径发现和知识缺口识别功能
|
||||
"""
|
||||
|
||||
def __init__(self, db_path: str = "insightflow.db"):
|
||||
def __init__(self, db_path: str = "insightflow.db") -> None:
|
||||
self.db_path = db_path
|
||||
self.fulltext_search = FullTextSearch(db_path)
|
||||
self.semantic_search = SemanticSearch(db_path)
|
||||
|
||||
@@ -195,7 +195,7 @@ class SecurityManager:
|
||||
},
|
||||
}
|
||||
|
||||
def __init__(self, db_path: str = "insightflow.db"):
|
||||
def __init__(self, db_path: str = "insightflow.db") -> None:
|
||||
self.db_path = db_path
|
||||
# 预编译正则缓存
|
||||
self._compiled_patterns: dict[str, re.Pattern] = {}
|
||||
|
||||
@@ -313,7 +313,7 @@ class SubscriptionManager:
|
||||
"export": {"unit": "page", "price": 0.1, "free_quota": 100}, # 0.1元/页(PDF导出)
|
||||
}
|
||||
|
||||
def __init__(self, db_path: str = "insightflow.db"):
|
||||
def __init__(self, db_path: str = "insightflow.db") -> None:
|
||||
self.db_path = db_path
|
||||
self._init_db()
|
||||
self._init_default_plans()
|
||||
@@ -1822,7 +1822,7 @@ class SubscriptionManager:
|
||||
description: str,
|
||||
reference_id: str,
|
||||
balance_after: float,
|
||||
):
|
||||
) -> None:
|
||||
"""内部方法:添加账单历史"""
|
||||
history_id = str(uuid.uuid4())
|
||||
|
||||
|
||||
@@ -257,7 +257,7 @@ class TenantManager:
|
||||
"export:basic": "基础导出",
|
||||
}
|
||||
|
||||
def __init__(self, db_path: str = "insightflow.db"):
|
||||
def __init__(self, db_path: str = "insightflow.db") -> None:
|
||||
self.db_path = db_path
|
||||
self._init_db()
|
||||
|
||||
@@ -1227,7 +1227,7 @@ class TenantManager:
|
||||
projects_count: int = 0,
|
||||
entities_count: int = 0,
|
||||
members_count: int = 0,
|
||||
):
|
||||
) -> None:
|
||||
"""记录资源使用"""
|
||||
conn = self._get_connection()
|
||||
try:
|
||||
@@ -1467,7 +1467,7 @@ class TenantManager:
|
||||
email: str,
|
||||
role: TenantRole,
|
||||
invited_by: str | None,
|
||||
):
|
||||
) -> None:
|
||||
"""内部方法:添加成员"""
|
||||
cursor = conn.cursor()
|
||||
member_id = str(uuid.uuid4())
|
||||
|
||||
@@ -21,7 +21,7 @@ from search_manager import (
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def test_fulltext_search():
|
||||
def test_fulltext_search() -> None:
|
||||
"""测试全文搜索"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试全文搜索 (FullTextSearch)")
|
||||
@@ -64,7 +64,7 @@ def test_fulltext_search():
|
||||
return True
|
||||
|
||||
|
||||
def test_semantic_search():
|
||||
def test_semantic_search() -> None:
|
||||
"""测试语义搜索"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试语义搜索 (SemanticSearch)")
|
||||
@@ -100,7 +100,7 @@ def test_semantic_search():
|
||||
return True
|
||||
|
||||
|
||||
def test_entity_path_discovery():
|
||||
def test_entity_path_discovery() -> None:
|
||||
"""测试实体路径发现"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试实体路径发现 (EntityPathDiscovery)")
|
||||
@@ -119,7 +119,7 @@ def test_entity_path_discovery():
|
||||
return True
|
||||
|
||||
|
||||
def test_knowledge_gap_detection():
|
||||
def test_knowledge_gap_detection() -> None:
|
||||
"""测试知识缺口识别"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试知识缺口识别 (KnowledgeGapDetection)")
|
||||
@@ -138,7 +138,7 @@ def test_knowledge_gap_detection():
|
||||
return True
|
||||
|
||||
|
||||
def test_cache_manager():
|
||||
def test_cache_manager() -> None:
|
||||
"""测试缓存管理器"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试缓存管理器 (CacheManager)")
|
||||
@@ -186,7 +186,7 @@ def test_cache_manager():
|
||||
return True
|
||||
|
||||
|
||||
def test_task_queue():
|
||||
def test_task_queue() -> None:
|
||||
"""测试任务队列"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试任务队列 (TaskQueue)")
|
||||
@@ -200,7 +200,7 @@ def test_task_queue():
|
||||
print("\n2. 测试任务提交...")
|
||||
|
||||
# 定义测试任务处理器
|
||||
def test_task_handler(payload):
|
||||
def test_task_handler(payload) -> None:
|
||||
print(f" 执行任务: {payload}")
|
||||
return {"status": "success", "processed": True}
|
||||
|
||||
@@ -227,7 +227,7 @@ def test_task_queue():
|
||||
return True
|
||||
|
||||
|
||||
def test_performance_monitor():
|
||||
def test_performance_monitor() -> None:
|
||||
"""测试性能监控"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试性能监控 (PerformanceMonitor)")
|
||||
@@ -274,7 +274,7 @@ def test_performance_monitor():
|
||||
return True
|
||||
|
||||
|
||||
def test_search_manager():
|
||||
def test_search_manager() -> None:
|
||||
"""测试搜索管理器"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试搜索管理器 (SearchManager)")
|
||||
@@ -295,7 +295,7 @@ def test_search_manager():
|
||||
return True
|
||||
|
||||
|
||||
def test_performance_manager():
|
||||
def test_performance_manager() -> None:
|
||||
"""测试性能管理器"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试性能管理器 (PerformanceManager)")
|
||||
@@ -320,7 +320,7 @@ def test_performance_manager():
|
||||
return True
|
||||
|
||||
|
||||
def run_all_tests():
|
||||
def run_all_tests() -> None:
|
||||
"""运行所有测试"""
|
||||
print("\n" + " = " * 60)
|
||||
print("InsightFlow Phase 7 Task 6 & 8 测试")
|
||||
|
||||
@@ -18,7 +18,7 @@ from tenant_manager import get_tenant_manager
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def test_tenant_management():
|
||||
def test_tenant_management() -> None:
|
||||
"""测试租户管理功能"""
|
||||
print(" = " * 60)
|
||||
print("测试 1: 租户管理")
|
||||
@@ -66,7 +66,7 @@ def test_tenant_management():
|
||||
return tenant.id
|
||||
|
||||
|
||||
def test_domain_management(tenant_id: str):
|
||||
def test_domain_management(tenant_id: str) -> None:
|
||||
"""测试域名管理功能"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试 2: 域名管理")
|
||||
@@ -112,7 +112,7 @@ def test_domain_management(tenant_id: str):
|
||||
return domain.id
|
||||
|
||||
|
||||
def test_branding_management(tenant_id: str):
|
||||
def test_branding_management(tenant_id: str) -> None:
|
||||
"""测试品牌白标功能"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试 3: 品牌白标")
|
||||
@@ -152,7 +152,7 @@ def test_branding_management(tenant_id: str):
|
||||
return branding.id
|
||||
|
||||
|
||||
def test_member_management(tenant_id: str):
|
||||
def test_member_management(tenant_id: str) -> None:
|
||||
"""测试成员管理功能"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试 4: 成员管理")
|
||||
@@ -207,7 +207,7 @@ def test_member_management(tenant_id: str):
|
||||
return member1.id, member2.id
|
||||
|
||||
|
||||
def test_usage_tracking(tenant_id: str):
|
||||
def test_usage_tracking(tenant_id: str) -> None:
|
||||
"""测试资源使用统计功能"""
|
||||
print("\n" + " = " * 60)
|
||||
print("测试 5: 资源使用统计")
|
||||
@@ -249,7 +249,7 @@ def test_usage_tracking(tenant_id: str):
|
||||
return stats
|
||||
|
||||
|
||||
def cleanup(tenant_id: str, domain_id: str, member_ids: list):
|
||||
def cleanup(tenant_id: str, domain_id: str, member_ids: list) -> None:
|
||||
"""清理测试数据"""
|
||||
print("\n" + " = " * 60)
|
||||
print("清理测试数据")
|
||||
@@ -273,7 +273,7 @@ def cleanup(tenant_id: str, domain_id: str, member_ids: list):
|
||||
print(f"✅ 租户已删除: {tenant_id}")
|
||||
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
"""主测试函数"""
|
||||
print("\n" + " = " * 60)
|
||||
print("InsightFlow Phase 8 Task 1 - 多租户 SaaS 架构测试")
|
||||
|
||||
@@ -12,7 +12,7 @@ from subscription_manager import PaymentProvider, SubscriptionManager
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def test_subscription_manager():
|
||||
def test_subscription_manager() -> None:
|
||||
"""测试订阅管理器"""
|
||||
print(" = " * 60)
|
||||
print("InsightFlow Phase 8 Task 2 - 订阅与计费系统测试")
|
||||
|
||||
@@ -14,7 +14,7 @@ from ai_manager import ModelType, PredictionType, get_ai_manager
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def test_custom_model():
|
||||
def test_custom_model() -> None:
|
||||
"""测试自定义模型功能"""
|
||||
print("\n=== 测试自定义模型 ===")
|
||||
|
||||
@@ -89,7 +89,7 @@ def test_custom_model():
|
||||
return model.id
|
||||
|
||||
|
||||
async def test_train_and_predict(model_id: str):
|
||||
async def test_train_and_predict(model_id: str) -> None:
|
||||
"""测试训练和预测"""
|
||||
print("\n=== 测试模型训练和预测 ===")
|
||||
|
||||
@@ -116,7 +116,7 @@ async def test_train_and_predict(model_id: str):
|
||||
print(f" 预测失败: {e}")
|
||||
|
||||
|
||||
def test_prediction_models():
|
||||
def test_prediction_models() -> None:
|
||||
"""测试预测模型"""
|
||||
print("\n=== 测试预测模型 ===")
|
||||
|
||||
@@ -158,7 +158,7 @@ def test_prediction_models():
|
||||
return trend_model.id, anomaly_model.id
|
||||
|
||||
|
||||
async def test_predictions(trend_model_id: str, anomaly_model_id: str):
|
||||
async def test_predictions(trend_model_id: str, anomaly_model_id: str) -> None:
|
||||
"""测试预测功能"""
|
||||
print("\n=== 测试预测功能 ===")
|
||||
|
||||
@@ -193,7 +193,7 @@ async def test_predictions(trend_model_id: str, anomaly_model_id: str):
|
||||
print(f" 检测结果: {anomaly_result.prediction_data}")
|
||||
|
||||
|
||||
def test_kg_rag():
|
||||
def test_kg_rag() -> None:
|
||||
"""测试知识图谱 RAG"""
|
||||
print("\n=== 测试知识图谱 RAG ===")
|
||||
|
||||
@@ -223,7 +223,7 @@ def test_kg_rag():
|
||||
return rag.id
|
||||
|
||||
|
||||
async def test_kg_rag_query(rag_id: str):
|
||||
async def test_kg_rag_query(rag_id: str) -> None:
|
||||
"""测试 RAG 查询"""
|
||||
print("\n=== 测试知识图谱 RAG 查询 ===")
|
||||
|
||||
@@ -294,7 +294,7 @@ async def test_kg_rag_query(rag_id: str):
|
||||
print(f" 查询失败: {e}")
|
||||
|
||||
|
||||
async def test_smart_summary():
|
||||
async def test_smart_summary() -> None:
|
||||
"""测试智能摘要"""
|
||||
print("\n=== 测试智能摘要 ===")
|
||||
|
||||
@@ -342,7 +342,7 @@ async def test_smart_summary():
|
||||
print(f" 生成失败: {e}")
|
||||
|
||||
|
||||
async def main():
|
||||
async def main() -> None:
|
||||
"""主测试函数"""
|
||||
print(" = " * 60)
|
||||
print("InsightFlow Phase 8 Task 4 - AI 能力增强测试")
|
||||
|
||||
@@ -36,13 +36,13 @@ if backend_dir not in sys.path:
|
||||
class TestGrowthManager:
|
||||
"""测试 Growth Manager 功能"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.manager = GrowthManager()
|
||||
self.test_tenant_id = "test_tenant_001"
|
||||
self.test_user_id = "test_user_001"
|
||||
self.test_results = []
|
||||
|
||||
def log(self, message: str, success: bool = True):
|
||||
def log(self, message: str, success: bool = True) -> None:
|
||||
"""记录测试结果"""
|
||||
status = "✅" if success else "❌"
|
||||
print(f"{status} {message}")
|
||||
@@ -50,7 +50,7 @@ class TestGrowthManager:
|
||||
|
||||
# ==================== 测试用户行为分析 ====================
|
||||
|
||||
async def test_track_event(self):
|
||||
async def test_track_event(self) -> None:
|
||||
"""测试事件追踪"""
|
||||
print("\n📊 测试事件追踪...")
|
||||
|
||||
@@ -77,7 +77,7 @@ class TestGrowthManager:
|
||||
self.log(f"事件追踪失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
async def test_track_multiple_events(self):
|
||||
async def test_track_multiple_events(self) -> None:
|
||||
"""测试追踪多个事件"""
|
||||
print("\n📊 测试追踪多个事件...")
|
||||
|
||||
@@ -104,7 +104,7 @@ class TestGrowthManager:
|
||||
self.log(f"批量事件追踪失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
def test_get_user_profile(self):
|
||||
def test_get_user_profile(self) -> None:
|
||||
"""测试获取用户画像"""
|
||||
print("\n👤 测试用户画像...")
|
||||
|
||||
@@ -123,7 +123,7 @@ class TestGrowthManager:
|
||||
self.log(f"获取用户画像失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
def test_get_analytics_summary(self):
|
||||
def test_get_analytics_summary(self) -> None:
|
||||
"""测试获取分析汇总"""
|
||||
print("\n📈 测试分析汇总...")
|
||||
|
||||
@@ -144,7 +144,7 @@ class TestGrowthManager:
|
||||
self.log(f"获取分析汇总失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
def test_create_funnel(self):
|
||||
def test_create_funnel(self) -> None:
|
||||
"""测试创建转化漏斗"""
|
||||
print("\n🎯 测试创建转化漏斗...")
|
||||
|
||||
@@ -171,7 +171,7 @@ class TestGrowthManager:
|
||||
self.log(f"创建漏斗失败: {e}", success = False)
|
||||
return None
|
||||
|
||||
def test_analyze_funnel(self, funnel_id: str):
|
||||
def test_analyze_funnel(self, funnel_id: str) -> None:
|
||||
"""测试分析漏斗"""
|
||||
print("\n📉 测试漏斗分析...")
|
||||
|
||||
@@ -197,7 +197,7 @@ class TestGrowthManager:
|
||||
self.log(f"漏斗分析失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
def test_calculate_retention(self):
|
||||
def test_calculate_retention(self) -> None:
|
||||
"""测试留存率计算"""
|
||||
print("\n🔄 测试留存率计算...")
|
||||
|
||||
@@ -219,7 +219,7 @@ class TestGrowthManager:
|
||||
|
||||
# ==================== 测试 A/B 测试框架 ====================
|
||||
|
||||
def test_create_experiment(self):
|
||||
def test_create_experiment(self) -> None:
|
||||
"""测试创建实验"""
|
||||
print("\n🧪 测试创建 A/B 测试实验...")
|
||||
|
||||
@@ -253,7 +253,7 @@ class TestGrowthManager:
|
||||
self.log(f"创建实验失败: {e}", success = False)
|
||||
return None
|
||||
|
||||
def test_list_experiments(self):
|
||||
def test_list_experiments(self) -> None:
|
||||
"""测试列出实验"""
|
||||
print("\n📋 测试列出实验...")
|
||||
|
||||
@@ -266,7 +266,7 @@ class TestGrowthManager:
|
||||
self.log(f"列出实验失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
def test_assign_variant(self, experiment_id: str):
|
||||
def test_assign_variant(self, experiment_id: str) -> None:
|
||||
"""测试分配变体"""
|
||||
print("\n🎲 测试分配实验变体...")
|
||||
|
||||
@@ -298,7 +298,7 @@ class TestGrowthManager:
|
||||
self.log(f"变体分配失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
def test_record_experiment_metric(self, experiment_id: str):
|
||||
def test_record_experiment_metric(self, experiment_id: str) -> None:
|
||||
"""测试记录实验指标"""
|
||||
print("\n📊 测试记录实验指标...")
|
||||
|
||||
@@ -331,7 +331,7 @@ class TestGrowthManager:
|
||||
self.log(f"记录指标失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
def test_analyze_experiment(self, experiment_id: str):
|
||||
def test_analyze_experiment(self, experiment_id: str) -> None:
|
||||
"""测试分析实验结果"""
|
||||
print("\n📈 测试分析实验结果...")
|
||||
|
||||
@@ -354,7 +354,7 @@ class TestGrowthManager:
|
||||
|
||||
# ==================== 测试邮件营销 ====================
|
||||
|
||||
def test_create_email_template(self):
|
||||
def test_create_email_template(self) -> None:
|
||||
"""测试创建邮件模板"""
|
||||
print("\n📧 测试创建邮件模板...")
|
||||
|
||||
@@ -388,7 +388,7 @@ class TestGrowthManager:
|
||||
self.log(f"创建邮件模板失败: {e}", success = False)
|
||||
return None
|
||||
|
||||
def test_list_email_templates(self):
|
||||
def test_list_email_templates(self) -> None:
|
||||
"""测试列出邮件模板"""
|
||||
print("\n📧 测试列出邮件模板...")
|
||||
|
||||
@@ -401,7 +401,7 @@ class TestGrowthManager:
|
||||
self.log(f"列出邮件模板失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
def test_render_template(self, template_id: str):
|
||||
def test_render_template(self, template_id: str) -> None:
|
||||
"""测试渲染邮件模板"""
|
||||
print("\n🎨 测试渲染邮件模板...")
|
||||
|
||||
@@ -430,7 +430,7 @@ class TestGrowthManager:
|
||||
self.log(f"模板渲染失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
def test_create_email_campaign(self, template_id: str):
|
||||
def test_create_email_campaign(self, template_id: str) -> None:
|
||||
"""测试创建邮件营销活动"""
|
||||
print("\n📮 测试创建邮件营销活动...")
|
||||
|
||||
@@ -459,7 +459,7 @@ class TestGrowthManager:
|
||||
self.log(f"创建营销活动失败: {e}", success = False)
|
||||
return None
|
||||
|
||||
def test_create_automation_workflow(self):
|
||||
def test_create_automation_workflow(self) -> None:
|
||||
"""测试创建自动化工作流"""
|
||||
print("\n🤖 测试创建自动化工作流...")
|
||||
|
||||
@@ -488,7 +488,7 @@ class TestGrowthManager:
|
||||
|
||||
# ==================== 测试推荐系统 ====================
|
||||
|
||||
def test_create_referral_program(self):
|
||||
def test_create_referral_program(self) -> None:
|
||||
"""测试创建推荐计划"""
|
||||
print("\n🎁 测试创建推荐计划...")
|
||||
|
||||
@@ -515,7 +515,7 @@ class TestGrowthManager:
|
||||
self.log(f"创建推荐计划失败: {e}", success = False)
|
||||
return None
|
||||
|
||||
def test_generate_referral_code(self, program_id: str):
|
||||
def test_generate_referral_code(self, program_id: str) -> None:
|
||||
"""测试生成推荐码"""
|
||||
print("\n🔑 测试生成推荐码...")
|
||||
|
||||
@@ -541,7 +541,7 @@ class TestGrowthManager:
|
||||
self.log(f"生成推荐码失败: {e}", success = False)
|
||||
return None
|
||||
|
||||
def test_apply_referral_code(self, referral_code: str):
|
||||
def test_apply_referral_code(self, referral_code: str) -> None:
|
||||
"""测试应用推荐码"""
|
||||
print("\n✅ 测试应用推荐码...")
|
||||
|
||||
@@ -564,7 +564,7 @@ class TestGrowthManager:
|
||||
self.log(f"应用推荐码失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
def test_get_referral_stats(self, program_id: str):
|
||||
def test_get_referral_stats(self, program_id: str) -> None:
|
||||
"""测试获取推荐统计"""
|
||||
print("\n📊 测试获取推荐统计...")
|
||||
|
||||
@@ -586,7 +586,7 @@ class TestGrowthManager:
|
||||
self.log(f"获取推荐统计失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
def test_create_team_incentive(self):
|
||||
def test_create_team_incentive(self) -> None:
|
||||
"""测试创建团队激励"""
|
||||
print("\n🏆 测试创建团队升级激励...")
|
||||
|
||||
@@ -612,7 +612,7 @@ class TestGrowthManager:
|
||||
self.log(f"创建团队激励失败: {e}", success = False)
|
||||
return False
|
||||
|
||||
def test_check_team_incentive_eligibility(self):
|
||||
def test_check_team_incentive_eligibility(self) -> None:
|
||||
"""测试检查团队激励资格"""
|
||||
print("\n🔍 测试检查团队激励资格...")
|
||||
|
||||
@@ -629,7 +629,7 @@ class TestGrowthManager:
|
||||
|
||||
# ==================== 测试实时仪表板 ====================
|
||||
|
||||
def test_get_realtime_dashboard(self):
|
||||
def test_get_realtime_dashboard(self) -> None:
|
||||
"""测试获取实时仪表板"""
|
||||
print("\n📺 测试实时分析仪表板...")
|
||||
|
||||
@@ -651,7 +651,7 @@ class TestGrowthManager:
|
||||
|
||||
# ==================== 运行所有测试 ====================
|
||||
|
||||
async def run_all_tests(self):
|
||||
async def run_all_tests(self) -> None:
|
||||
"""运行所有测试"""
|
||||
print(" = " * 60)
|
||||
print("🚀 InsightFlow Phase 8 Task 5 - 运营与增长工具测试")
|
||||
@@ -736,7 +736,7 @@ class TestGrowthManager:
|
||||
print(" = " * 60)
|
||||
|
||||
|
||||
async def main():
|
||||
async def main() -> None:
|
||||
"""主函数"""
|
||||
tester = TestGrowthManager()
|
||||
await tester.run_all_tests()
|
||||
|
||||
@@ -33,7 +33,7 @@ if backend_dir not in sys.path:
|
||||
class TestDeveloperEcosystem:
|
||||
"""开发者生态系统测试类"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.manager = DeveloperEcosystemManager()
|
||||
self.test_results = []
|
||||
self.created_ids = {
|
||||
@@ -45,7 +45,7 @@ class TestDeveloperEcosystem:
|
||||
"portal_config": [],
|
||||
}
|
||||
|
||||
def log(self, message: str, success: bool = True):
|
||||
def log(self, message: str, success: bool = True) -> None:
|
||||
"""记录测试结果"""
|
||||
status = "✅" if success else "❌"
|
||||
print(f"{status} {message}")
|
||||
@@ -53,7 +53,7 @@ class TestDeveloperEcosystem:
|
||||
{"message": message, "success": success, "timestamp": datetime.now().isoformat()}
|
||||
)
|
||||
|
||||
def run_all_tests(self):
|
||||
def run_all_tests(self) -> None:
|
||||
"""运行所有测试"""
|
||||
print(" = " * 60)
|
||||
print("InsightFlow Phase 8 Task 6: Developer Ecosystem Tests")
|
||||
@@ -119,7 +119,7 @@ class TestDeveloperEcosystem:
|
||||
# Print Summary
|
||||
self.print_summary()
|
||||
|
||||
def test_sdk_create(self):
|
||||
def test_sdk_create(self) -> None:
|
||||
"""测试创建 SDK"""
|
||||
try:
|
||||
sdk = self.manager.create_sdk_release(
|
||||
@@ -164,7 +164,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to create SDK: {str(e)}", success = False)
|
||||
|
||||
def test_sdk_list(self):
|
||||
def test_sdk_list(self) -> None:
|
||||
"""测试列出 SDK"""
|
||||
try:
|
||||
sdks = self.manager.list_sdk_releases()
|
||||
@@ -181,7 +181,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to list SDKs: {str(e)}", success = False)
|
||||
|
||||
def test_sdk_get(self):
|
||||
def test_sdk_get(self) -> None:
|
||||
"""测试获取 SDK 详情"""
|
||||
try:
|
||||
if self.created_ids["sdk"]:
|
||||
@@ -193,7 +193,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to get SDK: {str(e)}", success = False)
|
||||
|
||||
def test_sdk_update(self):
|
||||
def test_sdk_update(self) -> None:
|
||||
"""测试更新 SDK"""
|
||||
try:
|
||||
if self.created_ids["sdk"]:
|
||||
@@ -205,7 +205,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to update SDK: {str(e)}", success = False)
|
||||
|
||||
def test_sdk_publish(self):
|
||||
def test_sdk_publish(self) -> None:
|
||||
"""测试发布 SDK"""
|
||||
try:
|
||||
if self.created_ids["sdk"]:
|
||||
@@ -215,7 +215,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to publish SDK: {str(e)}", success = False)
|
||||
|
||||
def test_sdk_version_add(self):
|
||||
def test_sdk_version_add(self) -> None:
|
||||
"""测试添加 SDK 版本"""
|
||||
try:
|
||||
if self.created_ids["sdk"]:
|
||||
@@ -232,7 +232,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to add SDK version: {str(e)}", success = False)
|
||||
|
||||
def test_template_create(self):
|
||||
def test_template_create(self) -> None:
|
||||
"""测试创建模板"""
|
||||
try:
|
||||
template = self.manager.create_template(
|
||||
@@ -275,7 +275,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to create template: {str(e)}", success = False)
|
||||
|
||||
def test_template_list(self):
|
||||
def test_template_list(self) -> None:
|
||||
"""测试列出模板"""
|
||||
try:
|
||||
templates = self.manager.list_templates()
|
||||
@@ -292,7 +292,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to list templates: {str(e)}", success = False)
|
||||
|
||||
def test_template_get(self):
|
||||
def test_template_get(self) -> None:
|
||||
"""测试获取模板详情"""
|
||||
try:
|
||||
if self.created_ids["template"]:
|
||||
@@ -302,7 +302,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to get template: {str(e)}", success = False)
|
||||
|
||||
def test_template_approve(self):
|
||||
def test_template_approve(self) -> None:
|
||||
"""测试审核通过模板"""
|
||||
try:
|
||||
if self.created_ids["template"]:
|
||||
@@ -314,7 +314,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to approve template: {str(e)}", success = False)
|
||||
|
||||
def test_template_publish(self):
|
||||
def test_template_publish(self) -> None:
|
||||
"""测试发布模板"""
|
||||
try:
|
||||
if self.created_ids["template"]:
|
||||
@@ -324,7 +324,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to publish template: {str(e)}", success = False)
|
||||
|
||||
def test_template_review(self):
|
||||
def test_template_review(self) -> None:
|
||||
"""测试添加模板评价"""
|
||||
try:
|
||||
if self.created_ids["template"]:
|
||||
@@ -340,7 +340,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to add template review: {str(e)}", success = False)
|
||||
|
||||
def test_plugin_create(self):
|
||||
def test_plugin_create(self) -> None:
|
||||
"""测试创建插件"""
|
||||
try:
|
||||
plugin = self.manager.create_plugin(
|
||||
@@ -386,7 +386,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to create plugin: {str(e)}", success = False)
|
||||
|
||||
def test_plugin_list(self):
|
||||
def test_plugin_list(self) -> None:
|
||||
"""测试列出插件"""
|
||||
try:
|
||||
plugins = self.manager.list_plugins()
|
||||
@@ -399,7 +399,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to list plugins: {str(e)}", success = False)
|
||||
|
||||
def test_plugin_get(self):
|
||||
def test_plugin_get(self) -> None:
|
||||
"""测试获取插件详情"""
|
||||
try:
|
||||
if self.created_ids["plugin"]:
|
||||
@@ -409,7 +409,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to get plugin: {str(e)}", success = False)
|
||||
|
||||
def test_plugin_review(self):
|
||||
def test_plugin_review(self) -> None:
|
||||
"""测试审核插件"""
|
||||
try:
|
||||
if self.created_ids["plugin"]:
|
||||
@@ -424,7 +424,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to review plugin: {str(e)}", success = False)
|
||||
|
||||
def test_plugin_publish(self):
|
||||
def test_plugin_publish(self) -> None:
|
||||
"""测试发布插件"""
|
||||
try:
|
||||
if self.created_ids["plugin"]:
|
||||
@@ -434,7 +434,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to publish plugin: {str(e)}", success = False)
|
||||
|
||||
def test_plugin_review_add(self):
|
||||
def test_plugin_review_add(self) -> None:
|
||||
"""测试添加插件评价"""
|
||||
try:
|
||||
if self.created_ids["plugin"]:
|
||||
@@ -450,7 +450,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to add plugin review: {str(e)}", success = False)
|
||||
|
||||
def test_developer_profile_create(self):
|
||||
def test_developer_profile_create(self) -> None:
|
||||
"""测试创建开发者档案"""
|
||||
try:
|
||||
# Generate unique user IDs
|
||||
@@ -481,7 +481,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to create developer profile: {str(e)}", success = False)
|
||||
|
||||
def test_developer_profile_get(self):
|
||||
def test_developer_profile_get(self) -> None:
|
||||
"""测试获取开发者档案"""
|
||||
try:
|
||||
if self.created_ids["developer"]:
|
||||
@@ -491,7 +491,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to get developer profile: {str(e)}", success = False)
|
||||
|
||||
def test_developer_verify(self):
|
||||
def test_developer_verify(self) -> None:
|
||||
"""测试验证开发者"""
|
||||
try:
|
||||
if self.created_ids["developer"]:
|
||||
@@ -503,7 +503,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to verify developer: {str(e)}", success = False)
|
||||
|
||||
def test_developer_stats_update(self):
|
||||
def test_developer_stats_update(self) -> None:
|
||||
"""测试更新开发者统计"""
|
||||
try:
|
||||
if self.created_ids["developer"]:
|
||||
@@ -515,7 +515,7 @@ class TestDeveloperEcosystem:
|
||||
except Exception as e:
|
||||
self.log(f"Failed to update developer stats: {str(e)}", success = False)
|
||||
|
||||
def test_code_example_create(self):
|
||||
def test_code_example_create(self) -> None:
|
||||
"""测试创建代码示例"""
|
||||
try:
|
||||
example = self.manager.create_code_example(
|
||||
@@ -564,7 +564,7 @@ console.log('Upload complete:', result.id);
|
||||
except Exception as e:
|
||||
self.log(f"Failed to create code example: {str(e)}", success = False)
|
||||
|
||||
def test_code_example_list(self):
|
||||
def test_code_example_list(self) -> None:
|
||||
"""测试列出代码示例"""
|
||||
try:
|
||||
examples = self.manager.list_code_examples()
|
||||
@@ -577,7 +577,7 @@ console.log('Upload complete:', result.id);
|
||||
except Exception as e:
|
||||
self.log(f"Failed to list code examples: {str(e)}", success = False)
|
||||
|
||||
def test_code_example_get(self):
|
||||
def test_code_example_get(self) -> None:
|
||||
"""测试获取代码示例详情"""
|
||||
try:
|
||||
if self.created_ids["code_example"]:
|
||||
@@ -589,7 +589,7 @@ console.log('Upload complete:', result.id);
|
||||
except Exception as e:
|
||||
self.log(f"Failed to get code example: {str(e)}", success = False)
|
||||
|
||||
def test_portal_config_create(self):
|
||||
def test_portal_config_create(self) -> None:
|
||||
"""测试创建开发者门户配置"""
|
||||
try:
|
||||
config = self.manager.create_portal_config(
|
||||
@@ -610,7 +610,7 @@ console.log('Upload complete:', result.id);
|
||||
except Exception as e:
|
||||
self.log(f"Failed to create portal config: {str(e)}", success = False)
|
||||
|
||||
def test_portal_config_get(self):
|
||||
def test_portal_config_get(self) -> None:
|
||||
"""测试获取开发者门户配置"""
|
||||
try:
|
||||
if self.created_ids["portal_config"]:
|
||||
@@ -626,7 +626,7 @@ console.log('Upload complete:', result.id);
|
||||
except Exception as e:
|
||||
self.log(f"Failed to get portal config: {str(e)}", success = False)
|
||||
|
||||
def test_revenue_record(self):
|
||||
def test_revenue_record(self) -> None:
|
||||
"""测试记录开发者收益"""
|
||||
try:
|
||||
if self.created_ids["developer"] and self.created_ids["plugin"]:
|
||||
@@ -646,7 +646,7 @@ console.log('Upload complete:', result.id);
|
||||
except Exception as e:
|
||||
self.log(f"Failed to record revenue: {str(e)}", success = False)
|
||||
|
||||
def test_revenue_summary(self):
|
||||
def test_revenue_summary(self) -> None:
|
||||
"""测试获取开发者收益汇总"""
|
||||
try:
|
||||
if self.created_ids["developer"]:
|
||||
@@ -661,7 +661,7 @@ console.log('Upload complete:', result.id);
|
||||
except Exception as e:
|
||||
self.log(f"Failed to get revenue summary: {str(e)}", success = False)
|
||||
|
||||
def print_summary(self):
|
||||
def print_summary(self) -> None:
|
||||
"""打印测试摘要"""
|
||||
print("\n" + " = " * 60)
|
||||
print("Test Summary")
|
||||
@@ -689,7 +689,7 @@ console.log('Upload complete:', result.id);
|
||||
print(" = " * 60)
|
||||
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
"""主函数"""
|
||||
test = TestDeveloperEcosystem()
|
||||
test.run_all_tests()
|
||||
|
||||
@@ -34,18 +34,18 @@ if backend_dir not in sys.path:
|
||||
class TestOpsManager:
|
||||
"""测试运维与监控管理器"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.manager = get_ops_manager()
|
||||
self.tenant_id = "test_tenant_001"
|
||||
self.test_results = []
|
||||
|
||||
def log(self, message: str, success: bool = True):
|
||||
def log(self, message: str, success: bool = True) -> None:
|
||||
"""记录测试结果"""
|
||||
status = "✅" if success else "❌"
|
||||
print(f"{status} {message}")
|
||||
self.test_results.append((message, success))
|
||||
|
||||
def run_all_tests(self):
|
||||
def run_all_tests(self) -> None:
|
||||
"""运行所有测试"""
|
||||
print(" = " * 60)
|
||||
print("InsightFlow Phase 8 Task 8: Operations & Monitoring Tests")
|
||||
@@ -73,7 +73,7 @@ class TestOpsManager:
|
||||
# 打印测试总结
|
||||
self.print_summary()
|
||||
|
||||
def test_alert_rules(self):
|
||||
def test_alert_rules(self) -> None:
|
||||
"""测试告警规则管理"""
|
||||
print("\n📋 Testing Alert Rules...")
|
||||
|
||||
@@ -142,7 +142,7 @@ class TestOpsManager:
|
||||
except Exception as e:
|
||||
self.log(f"Alert rules test failed: {e}", success = False)
|
||||
|
||||
def test_alert_channels(self):
|
||||
def test_alert_channels(self) -> None:
|
||||
"""测试告警渠道管理"""
|
||||
print("\n📢 Testing Alert Channels...")
|
||||
|
||||
@@ -205,7 +205,7 @@ class TestOpsManager:
|
||||
except Exception as e:
|
||||
self.log(f"Alert channels test failed: {e}", success = False)
|
||||
|
||||
def test_alerts(self):
|
||||
def test_alerts(self) -> None:
|
||||
"""测试告警管理"""
|
||||
print("\n🚨 Testing Alerts...")
|
||||
|
||||
@@ -328,7 +328,7 @@ class TestOpsManager:
|
||||
except Exception as e:
|
||||
self.log(f"Alerts test failed: {e}", success = False)
|
||||
|
||||
def test_capacity_planning(self):
|
||||
def test_capacity_planning(self) -> None:
|
||||
"""测试容量规划"""
|
||||
print("\n📊 Testing Capacity Planning...")
|
||||
|
||||
@@ -389,7 +389,7 @@ class TestOpsManager:
|
||||
except Exception as e:
|
||||
self.log(f"Capacity planning test failed: {e}", success = False)
|
||||
|
||||
def test_auto_scaling(self):
|
||||
def test_auto_scaling(self) -> None:
|
||||
"""测试自动扩缩容"""
|
||||
print("\n⚖️ Testing Auto Scaling...")
|
||||
|
||||
@@ -447,7 +447,7 @@ class TestOpsManager:
|
||||
except Exception as e:
|
||||
self.log(f"Auto scaling test failed: {e}", success = False)
|
||||
|
||||
def test_health_checks(self):
|
||||
def test_health_checks(self) -> None:
|
||||
"""测试健康检查"""
|
||||
print("\n💓 Testing Health Checks...")
|
||||
|
||||
@@ -486,7 +486,7 @@ class TestOpsManager:
|
||||
self.log(f"Listed {len(checks)} health checks")
|
||||
|
||||
# 执行健康检查(异步)
|
||||
async def run_health_check():
|
||||
async def run_health_check() -> None:
|
||||
result = await self.manager.execute_health_check(check1.id)
|
||||
return result
|
||||
|
||||
@@ -502,7 +502,7 @@ class TestOpsManager:
|
||||
except Exception as e:
|
||||
self.log(f"Health checks test failed: {e}", success = False)
|
||||
|
||||
def test_failover(self):
|
||||
def test_failover(self) -> None:
|
||||
"""测试故障转移"""
|
||||
print("\n🔄 Testing Failover...")
|
||||
|
||||
@@ -558,7 +558,7 @@ class TestOpsManager:
|
||||
except Exception as e:
|
||||
self.log(f"Failover test failed: {e}", success = False)
|
||||
|
||||
def test_backup(self):
|
||||
def test_backup(self) -> None:
|
||||
"""测试备份与恢复"""
|
||||
print("\n💾 Testing Backup & Recovery...")
|
||||
|
||||
@@ -612,7 +612,7 @@ class TestOpsManager:
|
||||
except Exception as e:
|
||||
self.log(f"Backup test failed: {e}", success = False)
|
||||
|
||||
def test_cost_optimization(self):
|
||||
def test_cost_optimization(self) -> None:
|
||||
"""测试成本优化"""
|
||||
print("\n💰 Testing Cost Optimization...")
|
||||
|
||||
@@ -700,7 +700,7 @@ class TestOpsManager:
|
||||
except Exception as e:
|
||||
self.log(f"Cost optimization test failed: {e}", success = False)
|
||||
|
||||
def print_summary(self):
|
||||
def print_summary(self) -> None:
|
||||
"""打印测试总结"""
|
||||
print("\n" + " = " * 60)
|
||||
print("Test Summary")
|
||||
@@ -723,7 +723,7 @@ class TestOpsManager:
|
||||
print(" = " * 60)
|
||||
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
"""主函数"""
|
||||
test = TestOpsManager()
|
||||
test.run_all_tests()
|
||||
|
||||
@@ -10,7 +10,7 @@ from typing import Any
|
||||
|
||||
|
||||
class TingwuClient:
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.access_key = os.getenv("ALI_ACCESS_KEY", "")
|
||||
self.secret_key = os.getenv("ALI_SECRET_KEY", "")
|
||||
self.endpoint = "https://tingwu.cn-beijing.aliyuncs.com"
|
||||
@@ -78,9 +78,6 @@ class TingwuClient:
|
||||
"""获取任务结果"""
|
||||
try:
|
||||
# 导入移到文件顶部会导致循环导入,保持在这里
|
||||
from alibabacloud_tea_openapi import models as open_api_models
|
||||
from alibabacloud_tingwu20230930 import models as tingwu_models
|
||||
from alibabacloud_tingwu20230930.client import Client as TingwuSDKClient
|
||||
|
||||
config = open_api_models.Config(
|
||||
access_key_id = self.access_key, access_key_secret = self.secret_key
|
||||
|
||||
@@ -96,7 +96,7 @@ class WorkflowTask:
|
||||
created_at: str = ""
|
||||
updated_at: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
def __post_init__(self) -> None:
|
||||
if not self.created_at:
|
||||
self.created_at = datetime.now().isoformat()
|
||||
if not self.updated_at:
|
||||
@@ -121,7 +121,7 @@ class WebhookConfig:
|
||||
success_count: int = 0
|
||||
fail_count: int = 0
|
||||
|
||||
def __post_init__(self):
|
||||
def __post_init__(self) -> None:
|
||||
if not self.created_at:
|
||||
self.created_at = datetime.now().isoformat()
|
||||
if not self.updated_at:
|
||||
@@ -151,7 +151,7 @@ class Workflow:
|
||||
success_count: int = 0
|
||||
fail_count: int = 0
|
||||
|
||||
def __post_init__(self):
|
||||
def __post_init__(self) -> None:
|
||||
if not self.created_at:
|
||||
self.created_at = datetime.now().isoformat()
|
||||
if not self.updated_at:
|
||||
@@ -174,7 +174,7 @@ class WorkflowLog:
|
||||
error_message: str = ""
|
||||
created_at: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
def __post_init__(self) -> None:
|
||||
if not self.created_at:
|
||||
self.created_at = datetime.now().isoformat()
|
||||
|
||||
@@ -182,7 +182,7 @@ class WorkflowLog:
|
||||
class WebhookNotifier:
|
||||
"""Webhook 通知器 - 支持飞书、钉钉、Slack"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.http_client = httpx.AsyncClient(timeout = 30.0)
|
||||
|
||||
async def send(self, config: WebhookConfig, message: dict) -> bool:
|
||||
@@ -330,7 +330,7 @@ class WebhookNotifier:
|
||||
|
||||
return True
|
||||
|
||||
async def close(self):
|
||||
async def close(self) -> None:
|
||||
"""关闭 HTTP 客户端"""
|
||||
await self.http_client.aclose()
|
||||
|
||||
@@ -343,7 +343,7 @@ class WorkflowManager:
|
||||
DEFAULT_RETRY_COUNT: int = 3
|
||||
DEFAULT_RETRY_DELAY: int = 5
|
||||
|
||||
def __init__(self, db_manager=None):
|
||||
def __init__(self, db_manager = None) -> None:
|
||||
self.db = db_manager
|
||||
self.scheduler = AsyncIOScheduler()
|
||||
self.notifier = WebhookNotifier()
|
||||
@@ -384,7 +384,7 @@ class WorkflowManager:
|
||||
self.scheduler.shutdown(wait = True)
|
||||
logger.info("Workflow scheduler stopped")
|
||||
|
||||
async def _load_and_schedule_workflows(self):
|
||||
async def _load_and_schedule_workflows(self) -> None:
|
||||
"""从数据库加载并调度所有活跃工作流"""
|
||||
try:
|
||||
workflows = self.list_workflows(status = "active")
|
||||
@@ -426,7 +426,7 @@ class WorkflowManager:
|
||||
f"Scheduled workflow {workflow.id} ({workflow.name}) with {workflow.schedule_type}"
|
||||
)
|
||||
|
||||
async def _execute_workflow_job(self, workflow_id: str):
|
||||
async def _execute_workflow_job(self, workflow_id: str) -> None:
|
||||
"""调度器调用的工作流执行函数"""
|
||||
try:
|
||||
await self.execute_workflow(workflow_id)
|
||||
@@ -1415,7 +1415,7 @@ class WorkflowManager:
|
||||
|
||||
async def _send_workflow_notification(
|
||||
self, workflow: Workflow, results: dict, success: bool = True
|
||||
):
|
||||
) -> None:
|
||||
"""发送工作流执行通知"""
|
||||
if not workflow.webhook_ids:
|
||||
return
|
||||
|
||||
@@ -55,7 +55,7 @@ def check_bare_excepts(content: str, file_path: Path) -> list[dict]:
|
||||
|
||||
for i, line in enumerate(lines, 1):
|
||||
stripped = line.strip()
|
||||
# 检查 except Exception: 或 except :
|
||||
# 检查 except Exception: 或 except Exception:
|
||||
if re.match(r'^except\s*:', stripped):
|
||||
issues.append({
|
||||
"line": i,
|
||||
@@ -333,7 +333,7 @@ def generate_report(all_issues: dict) -> str:
|
||||
|
||||
return '\n'.join(lines)
|
||||
|
||||
def git_commit_and_push():
|
||||
def git_commit_and_push() -> None:
|
||||
"""提交并推送代码"""
|
||||
try:
|
||||
os.chdir(PROJECT_PATH)
|
||||
@@ -371,7 +371,7 @@ def git_commit_and_push():
|
||||
except Exception as e:
|
||||
return f"❌ 错误: {e}"
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
"""主函数"""
|
||||
print("🔍 开始代码审查...")
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ class CodeIssue:
|
||||
issue_type: str,
|
||||
message: str,
|
||||
severity: str = "info",
|
||||
):
|
||||
) -> None:
|
||||
self.file_path = file_path
|
||||
self.line_no = line_no
|
||||
self.issue_type = issue_type
|
||||
@@ -24,12 +24,12 @@ class CodeIssue:
|
||||
self.severity = severity # info, warning, error
|
||||
self.fixed = False
|
||||
|
||||
def __repr__(self):
|
||||
def __repr__(self) -> None:
|
||||
return f"{self.severity.upper()}: {self.file_path}:{self.line_no} - {self.issue_type}: {self.message}"
|
||||
|
||||
|
||||
class CodeReviewer:
|
||||
def __init__(self, base_path: str):
|
||||
def __init__(self, base_path: str) -> None:
|
||||
self.base_path = Path(base_path)
|
||||
self.issues: list[CodeIssue] = []
|
||||
self.fixed_issues: list[CodeIssue] = []
|
||||
@@ -363,9 +363,9 @@ class CodeReviewer:
|
||||
idx = issue.line_no - 1
|
||||
if 0 <= idx < len(lines):
|
||||
line = lines[idx]
|
||||
# 将 except: 改为 except Exception:
|
||||
# 将 except Exception: 改为 except Exception:
|
||||
if re.search(r"except\s*:\s*$", line.strip()):
|
||||
lines[idx] = line.replace("except:", "except Exception:")
|
||||
lines[idx] = line.replace("except Exception:", "except Exception:")
|
||||
issue.fixed = True
|
||||
elif re.search(r"except\s+Exception\s*:\s*$", line.strip()):
|
||||
# 已经是 Exception,但可能需要更具体
|
||||
@@ -421,7 +421,7 @@ class CodeReviewer:
|
||||
return "\n".join(report)
|
||||
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
base_path = "/root/.openclaw/workspace/projects/insightflow/backend"
|
||||
reviewer = CodeReviewer(base_path)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user