Test_Agent/tests/base/mixins/smart_interaction.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

244 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 time
from tests.logger import get_logger
logger = get_logger("SmartInteraction")
class SmartInteractionMixin:
"""提供语义化点击、填写、选择等交互操作,带 JS 暴力兜底"""
def smart_click(self, text, role=None, timeout=5000):
"""语义化点击:带重试与可见性校验"""
logger.info(f"👉 [SmartClick] 尝试点击: {text}")
try:
el = self.smart_find(text, role=role, timeout=timeout)
el.wait_for(state="visible", timeout=timeout)
try:
el.click(timeout=timeout)
except Exception as e:
if "detached" in str(e).lower():
logger.warning(f"⚠️ 节点失效,正在重新寻找并点击: {text}")
self.smart_find(text, role=role, timeout=timeout).click(timeout=timeout)
else:
raise e
except Exception as e:
success = self.page.evaluate(f"""(txt) => {{
const target = Array.from(document.querySelectorAll('button, a, span, .p-button-label, label, input'))
.find(el => {{
const it = el.innerText.trim();
const al = el.getAttribute('aria-label') || "";
const ph = el.getAttribute('placeholder') || "";
return it.includes(txt) || al.includes(txt) || ph.includes(txt);
}});
if (target) {{
target.scrollIntoView({{behavior: "smooth", block: "center"}});
setTimeout(() => target.click(), 100);
return true;
}}
return false;
}}""", text)
if not success:
raise e
def smart_click_any(self, texts, role=None, timeout=5000):
"""按多个候选文案点击,兼容新旧页面元素文案"""
last_error = None
for text in texts:
try:
self.smart_click(text, role=role, timeout=timeout)
return text
except Exception as e:
last_error = e
logger.info(f" 候选元素未命中 [{text}]: {e}")
raise last_error or Exception(f"❌ 无法点击任一候选元素: {texts}")
def click_row_action(self, row_text, action_label, icon_classes=None, timeout=5000):
"""点击表格/卡片行内操作,兼容文本按钮、aria、tooltip 和图标按钮"""
icon_classes = icon_classes or []
logger.info(f"👉 [RowAction] 在 [{row_text}] 容器内点击 [{action_label}]")
result = self.page.evaluate("""([rowText, action, icons]) => {
const scopes = Array.from(document.querySelectorAll('tr, .p-datatable-row, .p-card, [role="row"], .group, .flex'))
.filter(el => {
const text = el.innerText || "";
const visible = el.offsetWidth > 0 && el.offsetHeight > 0;
return visible && text.includes(rowText);
})
.sort((a, b) => (a.innerText || "").length - (b.innerText || "").length);
for (const scope of scopes) {
const controls = Array.from(scope.querySelectorAll('button, a, [role="button"], .p-button'));
const byText = controls.find(el => {
const text = (el.innerText || "").trim();
const aria = el.getAttribute("aria-label") || "";
const title = el.getAttribute("title") || "";
const tooltip = el.getAttribute("data-p-tooltip") || el.getAttribute("data-pr-tooltip") || "";
return text.includes(action) || aria.includes(action) || title.includes(action) || tooltip.includes(action);
});
if (byText) {
byText.scrollIntoView({block: "center"});
byText.click();
return "CLICKED_TEXT";
}
for (const iconClass of icons) {
const icon = scope.querySelector(`.${iconClass.split(" ").join(".")}`);
const button = icon?.closest('button, a, [role="button"], .p-button');
if (button) {
button.scrollIntoView({block: "center"});
button.click();
return "CLICKED_ICON";
}
}
}
return "NOT_FOUND";
}""", [row_text, action_label, icon_classes])
if result != "NOT_FOUND":
logger.info(f" 行内操作命中: {result}")
return True
row = self.page.locator("tr, .p-datatable-row, .p-card, [role='row']").filter(has_text=row_text).first
row.wait_for(state="visible", timeout=timeout)
candidates = [
row.locator(f"button:has-text('{action_label}'), a:has-text('{action_label}'), [aria-label*='{action_label}']").first
]
for icon_class in icon_classes:
candidates.append(row.locator(f"button:has(.{icon_class.replace(' ', '.')}), a:has(.{icon_class.replace(' ', '.')})").first)
for loc in candidates:
try:
if loc.count() and loc.is_visible(timeout=500):
loc.click()
return True
except Exception:
continue
raise Exception(f"❌ 未找到 [{row_text}] 的行内操作 [{action_label}]")
def smart_fill(self, label, value, timeout=5000):
"""语义化输入:支持 Vue/React 的深度绑定注入"""
logger.info(f"⌨️ [SmartFill] 在 [{label}] 填写: {value}")
try:
el = self.smart_find(label, timeout=timeout)
el.wait_for(state="visible", timeout=timeout)
el.fill(value, timeout=timeout)
except Exception as first_err:
try:
logger.info(f"🔍 [SmartFill] 常规规则未命中,正在执行深度邻近探测 [{label}]...")
success = self.page.evaluate(f"""(lbl) => {{
document.querySelectorAll('[data-smart-target]').forEach(e => e.removeAttribute('data-smart-target'));
const allNodes = Array.from(document.querySelectorAll('label, span, div, p, legend'))
.filter(el => el.offsetWidth > 0 && el.offsetHeight > 0 && el.innerText && el.innerText.includes(lbl));
const tags = allNodes.filter(el => {{
return !Array.from(el.children).some(child => child.offsetWidth > 0 && child.innerText && child.innerText.includes(lbl));
}});
for (const t of tags) {{
const container = t.closest('.p-inputgroup, .field, .flex, div');
const input = container?.querySelector('input:not([type="hidden"]), textarea') ||
t.parentElement?.querySelector('input:not([type="hidden"]), textarea');
if (input && input.offsetWidth > 0) {{
input.setAttribute('data-smart-target', 'true');
return true;
}}
}}
return false;
}}""", label)
if success:
target = self.page.locator("[data-smart-target='true']").first
target.scroll_into_view_if_needed()
target.fill(value, timeout=timeout)
target.blur()
else:
logger.warning(f"⚠️ [SmartFill] JS 探测失败: 页面上可见区域内没找到 '{label}' 及其相邻输入框。")
raise first_err
except Exception as second_err:
logger.error(f"⚠️ [SmartFill] JS注入或执行时发生错误: {second_err}")
raise second_err
def smart_delete(self, text, role=None, timeout=5000):
logger.info(f"👉 [SmartDelete] 尝试删除: {text}")
try:
el = self.smart_find(text, role=role, timeout=timeout)
el.wait_for(state="visible", timeout=timeout)
el.click(timeout=timeout)
except Exception as e:
logger.error(f"⚠️ [SmartDelete] JS注入或执行时发生错误: {e}")
raise e
def smart_select(self, label, value):
"""智能下拉框选择 (适配 PrimeVue)"""
logger.info(f"📋 [SmartSelect] 在 [{label}] 下拉框寻找目标: {value}")
opened = self.page.evaluate("""([lbl, val]) => {
const root = document.querySelector('.p-dialog') || document.querySelector('[role="dialog"]') || document;
const elements = Array.from(root.querySelectorAll('label, span, div'));
const targetLabel = elements.find(el => {
const t = el.innerText?.trim();
return t && (t === lbl || t.includes(lbl)) && el.offsetWidth > 0;
});
if (!targetLabel) return 'NO_LABEL';
let container = targetLabel;
for (let i = 0; i < 8; i++) {
if (!container) break;
const dd = container.querySelector('.p-select, .p-dropdown, [data-pc-name="select"], [data-pc-name="dropdown"]');
if (dd && dd.offsetWidth > 0) {
dd.scrollIntoView({block: 'center'});
dd.click();
return 'OPENED';
}
if (container.parentElement) {
const sibling = container.parentElement.querySelector('.p-select, .p-dropdown, [data-pc-name="select"]');
if (sibling && sibling.offsetWidth > 0) {
sibling.scrollIntoView({block: 'center'});
sibling.click();
return 'OPENED';
}
}
container = container.parentElement;
}
return 'NO_DROPDOWN';
}""", [label, value])
if opened != 'OPENED':
logger.warning(f"⚠️ [SmartSelect] 无法精准找到标签 '{label}' 关联的下拉框,尝试直接搜索首个 visible 的下拉框...")
self.page.locator(".p-select, .p-dropdown").first.click()
time.sleep(1)
try:
selectors = [
f"li[role='option']:has-text('{value}')",
f".p-select-option:has-text('{value}')",
f".p-dropdown-item:has-text('{value}')"
]
for sel in selectors:
loc = self.page.locator(sel).first
if loc.is_visible(timeout=500):
loc.click()
logger.info(f"✅ [SmartSelect] 成功通过选择器选中: {value}")
return True
except Exception:
pass
clicked = self.page.evaluate("""(val) => {
const options = Array.from(document.querySelectorAll('li[role="option"], .p-select-option, .p-dropdown-item'));
const target = options.find(opt => opt.offsetWidth > 0 && opt.innerText.includes(val));
if (target) {
target.scrollIntoView({block: 'center'});
target.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));
return true;
}
return false;
}""", value)
if clicked:
logger.info(f"✅ [SmartSelect] 通过 JS 暴力匹配选中: {value}")
return True
raise Exception(f"❌ [SmartSelect] 无法在下拉框中选择选项: {value}")