TBC/agent/ui_analyzer.py

264 lines
11 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.

import re
import logging
from pathlib import Path
from dataclasses import dataclass, field
from typing import Optional
logger = logging.getLogger(__name__)
@dataclass
class UISelector:
type: str # css, text, xpath, placeholder, role, attribute
value: str
file: str
line: int
context: str
@dataclass
class UIChange:
selector: UISelector
found_in_frontend: bool
frontend_file: str = ""
frontend_line: int = 0
suggestion: str = ""
class UIAnalyzer:
SELECTOR_PATTERNS = [
(re.compile(r"""page\.locator\(['"]([^'"]+)['"]"""), "css"),
(re.compile(r"""page\.get_by_text\(['"]([^'"]+)['"]"""), "text"),
(re.compile(r"""page\.get_by_placeholder\(['"]([^'"]+)['"]"""), "placeholder"),
(re.compile(r"""page\.get_by_role\(['"]([^'"]+)['"]"""), "role"),
(re.compile(r"""locator\(['"]([^'"]+)['"]"""), "css"),
(re.compile(r"""click\(['"]([^'"]+)['"]"""), "text"),
(re.compile(r"""fill\(['"]([^'"]+)['"]"""), "css"),
(re.compile(r"""input\[placeholder\*=['"]([^'"]+)['"]"""), "css"),
(re.compile(r"""button\[class\*=['"]([^'"]+)['"]"""), "css"),
(re.compile(r"""button\.(\w+)"""), "css_class"),
(re.compile(r"""#form_item_(\w+)"""), "css_id"),
(re.compile(r"""text=['"]([^'"]+)['"]"""), "text"),
(re.compile(r"""'([^']+)'\)"\)"""), "text"),
]
FRONTEND_SEARCH_PATTERNS = [
(re.compile(r'[\'"]([^\'"]*BTN[^\'"]*)[\'"]', re.IGNORECASE), "btn"),
(re.compile(r'[\'"]([^\'"]*button[^\'"]*)[\'"]', re.IGNORECASE), "button"),
(re.compile(r'[\'"]([^\'"]*login[^\'"]*)[\'"]', re.IGNORECASE), "login"),
(re.compile(r'[\'"]([^\'"]*input[^\'"]*)[\'"]', re.IGNORECASE), "input"),
(re.compile(r'className\s*[=:]\s*[\'"]([^\'"]+)[\'"]'), "class"),
(re.compile(r'id\s*[=:]\s*[\'"]([^\'"]+)[\'"]'), "id"),
(re.compile(r'placeholder\s*[=:]\s*[\'"]([^\'"]+)[\'"]'), "placeholder"),
(re.compile(r'>\s*([^<]{2,30})\s*<'), "text"),
(re.compile(r'aria-label\s*[=:]\s*[\'"]([^\'"]+)[\'"]'), "aria"),
]
def __init__(self, robogo_dir: Path):
self.robogo_dir = Path(robogo_dir)
def extract_selectors(self) -> list[UISelector]:
selectors = []
scripts_dir = self.robogo_dir / "framework" / "scripts"
business_dir = self.robogo_dir / "framework" / "business"
core_dir = self.robogo_dir / "framework" / "core"
for search_dir in [scripts_dir, business_dir, core_dir]:
if not search_dir.exists():
continue
for py_file in search_dir.rglob("*.py"):
if py_file.name.startswith("__"):
continue
try:
source = py_file.read_text(encoding="utf-8")
for pattern, sel_type in self.SELECTOR_PATTERNS:
for match in pattern.finditer(source):
value = match.group(1).strip()
if len(value) < 2 or value.startswith("http"):
continue
line = source[:match.start()].count("\n") + 1
context_start = max(0, match.start() - 30)
context_end = min(len(source), match.end() + 30)
context = source[context_start:context_end].replace("\n", " ").strip()
selectors.append(UISelector(
type=sel_type,
value=value,
file=str(py_file.relative_to(self.robogo_dir)),
line=line,
context=context,
))
except Exception as e:
logger.warning(f"分析文件失败 {py_file}: {e}")
return selectors
def check_frontend(self, selectors: list[UISelector], frontend_dir: Path) -> list[UIChange]:
changes = []
frontend_files = list(frontend_dir.rglob("*"))
frontend_texts = {}
for f in frontend_files:
if f.is_file() and f.suffix in (".tsx", ".ts", ".jsx", ".js", ".vue", ".html", ".css", ".scss", ".less"):
try:
content = f.read_text(encoding="utf-8", errors="ignore")
frontend_texts[str(f.relative_to(frontend_dir))] = content
except Exception:
pass
for sel in selectors:
found = False
found_file = ""
found_line = 0
for fpath, content in frontend_texts.items():
if sel.value in content:
found = True
found_file = fpath
idx = content.find(sel.value)
found_line = content[:idx].count("\n") + 1
break
if not found:
for pattern, ptype in self.FRONTEND_SEARCH_PATTERNS:
if sel.value in ["", " ", " "]:
continue
for fpath, content in frontend_texts.items():
for m in pattern.finditer(content):
if sel.value.lower() in m.group(1).lower() or m.group(1).lower() in sel.value.lower():
found = True
found_file = fpath
found_line = content[:m.start()].count("\n") + 1
break
if found:
break
if found:
break
suggestion = ""
if not found:
suggestion = f"前端代码中未找到选择器 '{sel.value}',UI 元素可能已变更或移除"
changes.append(UIChange(
selector=sel,
found_in_frontend=found,
frontend_file=found_file,
frontend_line=found_line,
suggestion=suggestion,
))
return changes
def generate_report(self, changes: list[UIChange]) -> str:
missing = [c for c in changes if not c.found_in_frontend]
found = [c for c in changes if c.found_in_frontend]
lines = ["# Robogo UI 元素变更分析报告", "", f"## 总览", ""]
lines.append(f"- 总选择器: {len(changes)}")
lines.append(f"- 匹配成功: {len(found)}")
lines.append(f"- 可能变更: {len(missing)}")
lines.append(f"- 匹配率: {len(found)/len(changes)*100:.1f}%" if changes else "- 匹配率: N/A")
lines.append("")
if missing:
lines.append(f"## 需要关注的变更 ({len(missing)} 个)")
lines.append("")
lines.append("| 文件 | 行号 | 选择器类型 | 选择器值 | 上下文 |")
lines.append("|------|------|-----------|---------|--------|")
for c in missing[:50]:
lines.append(f"| {c.selector.file} | {c.selector.line} | {c.selector.type} | `{c.selector.value[:60]}` | {c.selector.context[:50]} |")
lines.append("")
if found:
lines.append(f"## 已确认匹配 ({len(found)} 个)")
lines.append("")
lines.append("| 测试文件 | 前端文件 | 选择器 |")
lines.append("|---------|---------|--------|")
for c in found[:30]:
lines.append(f"| {c.selector.file} | {c.frontend_file} | `{c.selector.value[:50]}` |")
return "\n".join(lines)
def build_llm_prompt(self, changes: list[UIChange], frontend_dir: Path) -> str:
missing = [c for c in changes if not c.found_in_frontend]
if not missing:
return ""
prompt_parts = [
"以下 Robogo 测试脚本中的 UI 选择器在前端代码中未找到对应元素,请分析变更原因并给出修复建议:",
"",
]
for c in missing[:20]:
prompt_parts.append(f"### {c.selector.file}:{c.selector.line}")
prompt_parts.append(f"- 类型: {c.selector.type}")
prompt_parts.append(f"- 选择器: `{c.selector.value}`")
prompt_parts.append(f"- 上下文: `{c.selector.context}`")
prompt_parts.append("")
prompt_parts.append("请为每个失效的选择器提供:")
prompt_parts.append("1. 变更原因分析")
prompt_parts.append("2. 建议的修复代码(新的选择器)")
prompt_parts.append("3. 受影响的其他测试代码")
return "\n".join(prompt_parts)
def build_fix_prompt(self, changes: list[UIChange], frontend_dir: Path, batch_idx: int = 0, batch_size: int = 1) -> str:
"""构建自动修复 prompt"""
missing = [c for c in changes if not c.found_in_frontend]
if not missing:
return ""
by_file = {}
for c in missing:
f = c.selector.file
if f not in by_file: by_file[f] = []
by_file[f].append(c)
file_list = list(by_file.items())
batch = file_list[batch_idx * batch_size : (batch_idx + 1) * batch_size]
if not batch:
return ""
prompt_parts = [
"你是一个 Playwright 自动化测试专家。请修复以下测试文件中的失效 UI 选择器。",
"重要:保持原有代码结构和逻辑完全不变,只修改失效的 UI 选择器。",
"",
]
for f, items in batch:
prompt_parts.append("## {} ({} 个失效选择器)".format(f, len(items)))
for c in items[:5]:
prompt_parts.append("- L{}: `{}` ({})".format(c.selector.line, c.selector.value[:50], c.selector.type))
prompt_parts.append("")
full_path = Path(f)
if full_path.exists():
orig = full_path.read_text(encoding="utf-8")
prompt_parts.append("原始文件:")
prompt_parts.append("```python")
prompt_parts.append(orig)
prompt_parts.append("```")
prompt_parts.append("")
prompt_parts.append("请输出修复后的完整文件代码,格式:```python:{}\n代码\n```".format(batch[0][0] if batch else ""))
return "\n".join(prompt_parts)
def apply_fixes(self, changes: list[UIChange], llm_response: str, output_dir: Path) -> dict:
"""解析 LLM 修复代码并写入文件"""
import re
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
fixed_files = {}
pattern = re.compile(r'```python:([^\n]+)\n(.*?)```', re.DOTALL)
for match in pattern.finditer(llm_response):
filepath = match.group(1).strip()
code = match.group(2).strip()
if code:
out_path = output_dir / filepath
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(code, encoding='utf-8')
fixed_files[filepath] = len(code)
return fixed_files