1. 为什么需要专门处理Checkbox和Radiobox?
在Web自动化测试中,表单元素的操作是最基础也是最频繁的交互场景。根据Selenium官方统计,表单测试用例占所有自动化测试用例的43%,其中checkbox和radiobox的操作错误率高达27%——这个数字远高于普通输入框和按钮。为什么这两种看似简单的控件会成为自动化测试的"重灾区"?
首先从技术实现上看,checkbox和radiobox在HTML中有三种存在形式:
- 标准原生控件:
<input type="checkbox">和<input type="radio"> - 自定义样式控件:通过CSS+JS模拟的伪控件
- 混合型控件:原生控件被隐藏,通过label关联触发
我在实际项目中遇到过这样一个案例:某电商平台的筛选条件使用了第三方的jstree组件实现多级checkbox,测试脚本运行时明明执行了点击操作,但页面状态就是没有变化。这就是典型的"伪checkbox"场景,需要特殊处理方式。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 基础操作:标准控件的处理方式
2.1 元素定位最佳实践
对于标准控件,推荐使用CSS选择器结合input标签属性定位:
python复制# 通过name和value定位特定radio
driver.find_element(By.CSS_SELECTOR, "input[type='radio'][name='gender'][value='male']")
# 通过id定位checkbox
driver.find_element(By.CSS_SELECTOR, "#agree_terms")
注意:避免使用XPath定位动态生成的控件,特别是React/Vue等框架构建的页面,元素的XPath可能会随渲染变化。
2.2 状态判断与操作
标准控件的核心操作方法:
python复制checkbox = driver.find_element(By.ID, "remember_me")
# 判断是否选中
is_selected = checkbox.is_selected()
# 选中操作(如果未选中)
if not is_selected:
checkbox.click()
# 取消选中(如果已选中)
else:
checkbox.click()
常见误区纠正:
- 不要直接使用
send_keys(Keys.SPACE)模拟空格键操作,不同浏览器兼容性差 - 避免重复点击,操作前务必检查当前状态
- 对于radio group,直接点击目标选项即可,无需先取消其他选项
3. 进阶实战:处理自定义样式控件
3.1 识别伪控件的三种方法
当标准操作失效时,说明遇到了自定义控件,可通过以下方式识别:
- 检查DOM结构:
html复制<!-- 真实input被隐藏 -->
<input type="checkbox" style="display:none">
<!-- 用div模拟视觉效果 -->
<div class="custom-checkbox"></div>
- 使用开发者工具检查事件监听:
- 在Chrome DevTools的Elements面板
- 找到疑似元素后查看Event Listeners
- 检查是否有自定义的click/change事件
- 执行JavaScript测试:
javascript复制// 在控制台尝试获取标准属性
document.querySelector('input[type="checkbox"]').checked
// 返回undefined说明不是标准控件
3.2 实战解决方案
案例:处理Element UI的半选状态checkbox
python复制# 定位实际的input元素(可能被隐藏)
hidden_checkbox = driver.find_element(By.XPATH, "//input[@type='checkbox']")
# 通过JavaScript直接修改状态
driver.execute_script("arguments[0].checked = true;", hidden_checkbox)
# 触发change事件
driver.execute_script("arguments[0].dispatchEvent(new Event('change'))", hidden_checkbox)
对于jstree等复杂组件,可能需要多层操作:
python复制# 先点击展开箭头(如果有)
driver.find_element(By.CSS_SELECTOR, ".jstree-ocl").click()
# 点击关联的label元素
driver.find_element(By.XPATH, "//label[@for='tree_node_1']").click()
4. 企业级测试框架中的最佳实践
4.1 封装通用操作类
建议在框架基础层封装Checkbox操作类:
python复制class CheckboxOperator:
def __init__(self, driver):
self.driver = driver
def set_checkbox(self, locator, state=True):
"""通用checkbox设置方法"""
element = self.driver.find_element(*locator)
current = element.is_selected()
if (state and not current) or (not state and current):
# 尝试标准点击
try:
element.click()
except:
# 回退到JS方式
self.driver.execute_script(
"arguments[0].checked = arguments[1];"
"arguments[0].dispatchEvent(new Event('change'));",
element, state
)
return self
4.2 处理动态加载的控件
对于AJAX加载的checkbox,需要使用显式等待:
python复制from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
checkbox = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, ".async-checkbox")
)
)
4.3 视觉验证方案
结合Allure报告添加状态截图:
python复制import allure
def test_checkbox_operation():
with allure.step("操作checkbox并验证"):
checkbox = CheckboxOperator(driver)
checkbox.set_checkbox((By.ID, "option1"), True)
# 添加带标注的截图
allure.attach(
driver.get_screenshot_as_png(),
name="checkbox_state",
attachment_type=allure.attachment_type.PNG
)
assert checkbox.is_selected()
5. 经典踩坑案例与排查指南
5.1 案例一:点击无效但无报错
现象:
- 脚本执行click()操作
- 页面无变化
- 控制台无任何错误
排查步骤:
- 检查元素是否被遮挡:
python复制from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_element(By.ID, "myCheckbox")
ActionChains(driver).move_to_element(element).perform()
- 检查是否有前置操作未完成(如需要先展开面板)
- 尝试改用label点击:
python复制driver.find_element(By.XPATH, "//label[@for='myCheckbox']").click()
5.2 案例二:状态判断不准确
现象:
- is_selected()返回False
- 但页面显示已选中
解决方案:
python复制# 检查是否通过CSS伪类实现状态
style = driver.execute_script(
"return window.getComputedStyle(arguments[0], '::before').content;",
element
)
if "✓" in style:
print("实际上是选中状态")
5.3 案例三:RadioGroup整体验证
对于互斥的radio按钮组,推荐验证方法:
python复制def verify_radio_group_selected(driver, name, expected_value):
"""验证radio group中指定选项被选中"""
selected = driver.execute_script(
f"return document.querySelector('input[name=\"{name}\"]:checked').value;"
)
assert selected == expected_value
6. 性能优化与跨浏览器方案
6.1 批量操作优化
当需要操作大量checkbox时(如全选表格行):
python复制# 低效方式(每个元素单独交互)
for checkbox in driver.find_elements(By.CLASS_NAME, "row-checkbox"):
checkbox.click()
# 优化方案(单次JS执行)
driver.execute_script("""
document.querySelectorAll('.row-checkbox').forEach(cb => {
cb.checked = true;
cb.dispatchEvent(new Event('change'));
});
""")
6.2 跨浏览器兼容方案
不同浏览器的特殊处理:
python复制def safe_click(element):
"""兼容各浏览器的点击方法"""
try:
element.click()
except:
# Edge特殊处理
if "edge" in driver.capabilities['browserName'].lower():
driver.execute_script("arguments[0].focus();", element)
element.send_keys(Keys.SPACE)
else:
raise
6.3 移动端适配技巧
对于Appium等移动端测试:
python复制# 触屏设备的长按操作
from appium.webdriver.common.touch_action import TouchAction
checkbox = driver.find_element(By.ID, "mobileCheckbox")
TouchAction(driver).long_press(checkbox).release().perform()
7. 与AI测试工具的结合实践
7.1 视觉定位辅助
当传统定位方式失效时,可结合CV技术:
python复制# 使用SikuliX的视觉定位
from sikuli import *
def click_checkbox_by_image(image_path):
region = Screen()
checkbox = region.find(image_path)
region.click(checkbox)
7.2 智能等待策略
基于页面变化的动态等待:
python复制def wait_for_checked_state(element, desired_state, timeout=10):
"""智能等待checkbox达到指定状态"""
def _predicate(driver):
current = element.is_selected()
if current == desired_state:
return True
# 检查是否通过CSS类名反映状态
class_state = "checked" in element.get_attribute("class")
return class_state == desired_state
WebDriverWait(driver, timeout).until(_predicate)
8. 企业级测试框架集成方案
8.1 与Pytest的深度整合
创建自定义fixture:
python复制import pytest
@pytest.fixture
def checkbox_operator(driver):
return CheckboxOperator(driver)
def test_features(checkbox_operator):
checkbox_operator.set_checkbox((By.ID, "feature_flag"), True)
# 其他测试逻辑
8.2 生成智能测试报告
使用pytest-html添加交互式元素状态:
python复制@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == "call":
# 添加checkbox状态快照
if "checkbox" in item.name:
extra = getattr(report, "extra", [])
extra.append(pytest_html.extras.html(
f'<div>Checkbox State: {driver.execute_script("return arguments[0].checked", element)}</div>'
))
report.extra = extra
9. 前沿技术:无头浏览器中的特殊处理
在Headless模式下的注意事项:
python复制# Chrome无头模式可能需要额外参数
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
options.add_argument("--disable-gpu")
options.add_argument("--window-size=1920,1080")
# 特别处理虚拟点击事件
driver.execute_cdp_cmd("Input.dispatchMouseEvent", {
"type": "mousePressed",
"x": element.location['x'] + 5,
"y": element.location['y'] + 5,
"button": "left",
"clickCount": 1
})
10. 安全测试中的特殊应用
处理不可见控件的安全测试:
python复制def test_hidden_checkbox_manipulation():
"""验证隐藏checkbox不能被普通用户操作"""
driver.execute_script(
"document.getElementById('admin_flag').style.display='block'"
)
try:
driver.find_element(By.ID, "admin_flag").click()
pytest.fail("Hidden checkbox should not be clickable")
except ElementNotInteractableException:
pass # 符合预期
11. 性能基准测试方案
测量操作响应时间:
python复制from time import perf_counter
def benchmark_checkbox_operation():
start = perf_counter()
for _ in range(100):
checkbox.click() # 切换状态
duration = perf_counter() - start
print(f"Average operation time: {duration/100*1000:.2f}ms")
assert duration/100 < 0.1 # 单次操作应小于100ms
12. 持续集成中的稳定方案
提高CI环境可靠性的技巧:
python复制# 重试机制
from tenacity import retry, stop_after_attempt
@retry(stop=stop_after_attempt(3))
def reliable_checkbox_operation(element):
element.click()
assert element.is_selected() # 验证状态变化
13. 无障碍测试(A11Y)整合
验证checkbox的可访问性:
python复制def test_checkbox_accessibility():
checkbox = driver.find_element(By.ID, "a11y_checkbox")
# 验证ARIA属性
assert checkbox.get_attribute("role") == "checkbox"
assert checkbox.get_attribute("aria-checked") in ["true", "false"]
# 验证关联的label
label_id = checkbox.get_attribute("aria-labelledby")
assert label_id in driver.page_source
14. 分布式测试中的同步策略
在多节点测试环境中:
python复制# 使用Redis共享状态
import redis
r = redis.Redis()
def sync_checkbox_state(node_id, element_id, state):
r.set(f"checkbox:{element_id}:{node_id}", str(state))
def get_consensus_state(element_id, node_count):
true_votes = sum(
1 for i in range(node_count)
if r.get(f"checkbox:{element_id}:{i}") == b"True"
)
return true_votes > node_count // 2
15. 测试数据工厂模式
动态生成测试用例:
python复制import itertools
def generate_checkbox_test_matrix():
states = [True, False]
browsers = ["chrome", "firefox", "edge"]
return itertools.product(states, browsers)
@pytest.mark.parametrize("state,browser", generate_checkbox_test_matrix())
def test_checkbox_matrix(state, browser):
with create_driver(browser) as driver:
operator = CheckboxOperator(driver)
operator.set_checkbox((By.ID, "test_box"), state)
assert operator.is_selected() == state
16. 错误注入测试技术
模拟异常场景:
python复制def test_checkbox_error_handling():
# 强制移除click事件监听
driver.execute_script("""
const el = document.getElementById('error_checkbox');
const newEl = el.cloneNode(true);
el.parentNode.replaceChild(newEl, el);
""")
try:
driver.find_element(By.ID, "error_checkbox").click()
except Exception as e:
assert "ElementNotInteractable" in str(e)
17. 可视化测试集成
结合Applitools进行视觉验证:
python复制from applitools.selenium import Eyes
def test_checkbox_visual():
eyes = Eyes()
eyes.open(driver, "Checkbox Test", "Visual Validation")
# 操作checkbox
checkbox = driver.find_element(By.ID, "visual_checkbox")
checkbox.click()
# 视觉验证
eyes.check_window("After Checkbox Click")
eyes.close()
18. 多语言站点的处理方案
处理国际化场景:
python复制def get_localized_checkbox(label_key, lang="en"):
# 从语言包获取对应文本
locator = f"//label[contains(text(), '{i18n[lang][label_key]}')]/input"
return driver.find_element(By.XPATH, locator)
19. 历史兼容性测试策略
处理老版本浏览器:
python复制def legacy_checkbox_click(element):
"""兼容IE11的特殊处理"""
if driver.capabilities['browserName'].lower() == 'internet explorer':
driver.execute_script("""
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true);
arguments[0].dispatchEvent(event);
""", element)
else:
element.click()
20. 调试技巧与开发工具集成
Chrome DevTools协议的高级用法:
python复制# 监听checkbox的状态变化事件
driver.execute_cdp_cmd("Runtime.addBinding", {
"name": "checkboxStateChanged"
})
driver.execute_cdp_cmd("Runtime.evaluate", {
"expression": """
document.querySelectorAll('input[type="checkbox"]').forEach(el => {
el.addEventListener('change', () => {
window.checkboxStateChanged(JSON.stringify({
id: el.id,
checked: el.checked
}));
});
});
"""
})
# 在Python端接收事件
def on_checkbox_state_changed(message):
print(f"Checkbox state changed: {message}")
driver.add_listener("Runtime.bindingCalled", lambda msg:
on_checkbox_state_changed(msg['payload']) if msg['name'] == 'checkboxStateChanged' else None
)
21. 移动端特殊手势处理
处理移动端长按多选模式:
python复制# 使用W3C Actions API实现长按
from selenium.webdriver.common.actions.action_builder import ActionBuilder
def mobile_long_press(element):
actions = ActionBuilder(driver)
finger = actions.add_pointer_input("touch", "finger")
finger.create_pointer_move(
duration=0,
x=element.location['x'],
y=element.location['y'],
origin="viewport"
)
finger.create_pointer_down(button=0)
finger.create_pause(1000) # 长按1秒
finger.create_pointer_up(button=0)
actions.perform()
22. 虚拟滚动列表中的优化
处理大数据量下的checkbox操作:
python复制def click_checkbox_in_virtual_scroll(row_text):
"""在虚拟滚动列表中定位并操作checkbox"""
while True:
try:
row = driver.find_element(
By.XPATH, f"//div[contains(text(), '{row_text}')]"
)
row.find_element(By.XPATH, "./preceding-sibling::input").click()
break
except:
# 滚动到底部则终止
if driver.execute_script(
"return window.scrollY + window.innerHeight >= document.body.scrollHeight"
):
raise
# 向下滚动一屏
driver.execute_script(
"window.scrollBy(0, window.innerHeight)"
)
23. 与状态管理工具的集成
测试Redux/Vuex状态同步:
python复制def test_checkbox_state_sync():
# 操作前端checkbox
driver.find_element(By.ID, "redux_checkbox").click()
# 验证Redux状态
redux_state = driver.execute_script(
"return window.store.getState().form.checked"
)
assert redux_state is True
24. 自动化修复策略
实现自修复测试逻辑:
python复制def resilient_checkbox_click(locator, max_attempts=3):
"""带自动修复的checkbox点击"""
for attempt in range(max_attempts):
try:
element = driver.find_element(*locator)
element.click()
if element.is_selected(): # 验证状态
return
except:
if attempt == max_attempts - 1:
raise
# 刷新页面重试
driver.refresh()
time.sleep(1)
25. 性能监控集成
在操作过程中收集性能指标:
python复制from selenium.webdriver.remote.command import Command
def instrumented_click(element):
"""带性能监控的点击操作"""
start = time.perf_counter()
element.click()
latency = time.perf_counter() - start
# 获取浏览器性能指标
perf = driver.execute(Command.GET_LOG, {"type": "performance"})['value']
return {
"operation_latency": latency,
"browser_metrics": perf
}
26. 跨标签页测试方案
处理多窗口场景:
python复制def test_checkbox_across_tabs():
# 主窗口操作
main_checkbox = driver.find_element(By.ID, "main_tab_checkbox")
main_checkbox.click()
# 打开新标签页
driver.switch_to.new_window('tab')
driver.get(secondary_url)
# 验证状态同步
secondary_checkbox = driver.find_element(By.ID, "secondary_tab_checkbox")
assert secondary_checkbox.is_selected()
# 返回主窗口
driver.switch_to.window(driver.window_handles[0])
assert main_checkbox.is_selected()
27. 与Web Components的交互
处理Shadow DOM中的元素:
python复制def click_shadow_checkbox():
# 穿透Shadow DOM定位
host = driver.find_element(By.CSS_SELECTOR, "custom-checkbox")
shadow_root = driver.execute_script("return arguments[0].shadowRoot", host)
checkbox = shadow_root.find_element(By.CSS_SELECTOR, "input[type='checkbox']")
checkbox.click()
28. 测试覆盖率统计
追踪checkbox操作路径:
python复制def track_checkbox_coverage():
# 注入监控代码
driver.execute_script("""
window.__checkboxCoverage = new Set();
document.querySelectorAll('input[type="checkbox"]').forEach(el => {
el.addEventListener('click', () => {
window.__checkboxCoverage.add(el.id);
});
});
""")
# 测试结束后获取覆盖率
covered = driver.execute_script("return Array.from(window.__checkboxCoverage)")
total = driver.execute_script(
"return document.querySelectorAll('input[type=\"checkbox\"]').length"
)
print(f"Checkbox coverage: {len(covered)}/{total}")
29. 与GraphQL的集成测试
验证后端状态同步:
python复制def test_checkbox_graphql_sync():
# 前端操作
driver.find_element(By.ID, "gql_checkbox").click()
# 通过GraphQL查询验证
query = """
query {
formState {
checkboxChecked
}
}
"""
response = requests.post(
graphql_endpoint,
json={"query": query},
headers={"Authorization": f"Bearer {token}"}
)
assert response.json()['data']['formState']['checkboxChecked'] is True
30. 混沌工程实践
模拟网络异常下的行为:
python复制def test_checkbox_under_chaos():
# 启用网络节流
driver.execute_cdp_cmd("Network.emulateNetworkConditions", {
"offline": False,
"latency": 1000, # 1秒延迟
"downloadThroughput": 500 * 1024, # 500KB/s
"uploadThroughput": 500 * 1024,
"connectionType": "cellular3g"
})
# 操作并验证超时处理
try:
WebDriverWait(driver, 2).until(
lambda d: d.find_element(By.ID, "chaos_checkbox").click()
)
except TimeoutException:
print("Behavior under poor network validated")
31. 与WebSocket的实时测试
测试实时更新的checkbox:
python复制def test_websocket_checkbox():
# 建立WebSocket监听
ws_url = driver.execute_script("return window.wsEndpoint")
ws = websockets.connect(ws_url)
# 操作前端checkbox
driver.find_element(By.ID, "realtime_checkbox").click()
# 验证WebSocket消息
message = json.loads(ws.recv())
assert message["type"] == "checkbox_update"
assert message["data"]["checked"] is True
32. 多因素组合测试
参数化组合验证:
python复制import hypothesis.strategies as st
from hypothesis import given
@given(
initial=st.booleans(),
to_click=st.booleans(),
delay=st.integers(min_value=0, max_value=1000)
)
def test_checkbox_combinations(initial, to_click, delay):
# 设置初始状态
driver.execute_script(
f"document.getElementById('combo_checkbox').checked = {str(initial).lower()}"
)
# 模拟操作延迟
time.sleep(delay / 1000)
# 执行点击
if to_click:
driver.find_element(By.ID, "combo_checkbox").click()
# 验证最终状态
final_state = driver.execute_script(
"return document.getElementById('combo_checkbox').checked"
)
assert final_state == (not initial if to_click else initial)
33. 可访问性自动化审计
集成axe-core进行自动化检测:
python复制def test_checkbox_a11y():
# 注入axe-core
driver.execute_script(open("axe.min.js").read())
# 运行检测
results = driver.execute_async_script("""
const callback = arguments[arguments.length - 1];
axe.run(document, {
runOnly: {
type: "tag",
values: ["wcag2a", "wcag2aa"]
}
}).then(callback);
""")
# 验证checkbox相关规则
checkbox_violations = [
v for v in results['violations']
if any(n['target'][0] == "input[type='checkbox']" for n in v['nodes'])
]
assert len(checkbox_violations) == 0
34. 视觉回归测试
使用Pixelmatch进行像素级比对:
python复制def test_checkbox_visual_regression():
# 获取初始截图
checkbox = driver.find_element(By.ID, "visual_checkbox")
initial = checkbox.screenshot_as_png
# 操作checkbox
checkbox.click()
# 获取新截图
updated = checkbox.screenshot_as_png
# 使用pixelmatch比较
diff = pixelmatch.compare(
initial, updated,
threshold=0.1, # 允许10%差异
includeAA=False
)
assert diff < 0.05 # 差异应小于5%
35. 国际化伪元素处理
处理不同语言的伪内容:
python复制def get_checkbox_i18n_state(element, lang):
"""获取伪元素本地化内容"""
return driver.execute_script("""
const styles = window.getComputedStyle(arguments[0], '::after');
const content = styles.content;
return content.includes(arguments[1]) ? content : null;
""", element, lang)
36. 内存泄漏检测
验证操作后的内存状态:
python复制def test_checkbox_memory():
# 获取初始内存快照
initial = driver.execute_script("return window.performance.memory")
# 执行多次checkbox操作
for _ in range(100):
driver.find_element(By.ID, "memory_checkbox").click()
# 获取新内存快照
current = driver.execute_script("return window.performance.memory")
# 验证内存增长不超过10%
assert current.usedJSHeapSize < initial.usedJSHeapSize * 1.1
37. 与IndexedDB的集成测试
验证本地存储同步:
python复制def test_checkbox_indexeddb():
# 操作前端checkbox
driver.find_element(By.ID, "persistent_checkbox").click()
# 读取IndexedDB验证
db_state = driver.execute_async_script("""
const callback = arguments[arguments.length - 1];
const req = indexedDB.open("formState");
req.onsuccess = () => {
const tx = req.result.transaction("checkboxes", "readonly");
const store = tx.objectStore("checkboxes");
store.get("preferences").onsuccess = e => callback(e.target.result);
};
""")
assert db_state["remember_me"] is True
38. 服务端渲染(SSR)验证
检测Hydration后的状态:
python复制def test_ssr_checkbox_hydration():
# 获取服务端渲染的初始HTML
initial_html = driver.page_source
# 等待客户端Hydration完成
WebDriverWait(driver, 5).until(
lambda d: d.execute_script(
"return window.__HYDRATION_COMPLETED__"
)
)
# 验证checkbox状态一致
server_checked = "checked" in initial_html
client_checked = driver.find_element(
By.ID, "hydrated_checkbox"
).is_selected()
assert server_checked == client_checked
39. 渐进式增强测试
验证无JS环境下的降级方案:
python复制def test_checkbox_fallback():
# 禁用JavaScript
driver.execute_cdp_cmd("Emulation.setScriptExecutionDisabled", {"value": True})
# 刷新页面
driver.refresh()
# 验证原生表单行为
checkbox = driver.find_element(By.ID, "fallback_checkbox")
assert checkbox.get_attribute("type") == "checkbox"
checkbox.click()
assert checkbox.get_attribute("checked") == "true"
40. 微前端架构测试
处理跨应用的checkbox状态:
python复制def test_microfrontend_checkbox():
# 主应用中的checkbox
main_app_checkbox = driver.find_element(
By.CSS_SELECTOR, "main-app input[type='checkbox']"
)
main_app_checkbox.click()
# 验证子应用状态
sub_app_state = driver.execute_script("""
return window.microfrontends.shoppingCart.getSharedState()
""")
assert sub_app_state["preferences"]["notifications"] is True
41. WebAssembly集成测试
验证与Wasm模块的交互:
python复制def test_wasm_checkbox():
# 操作checkbox
driver.find_element(By.ID, "wasm_checkbox").click()
# 调用Wasm模块验证
wasm_result = driver.execute_script("""
return window.wasmExports.validateCheckboxState(
document.getElementById('wasm_checkbox').checked
);
""")
assert wasm_result == 1 # 表示验证通过
42. Web Worker通信测试
验证后台线程中的状态处理:
python复制def test_worker_checkbox():
# 操作checkbox
driver.find_element(By.ID, "worker_checkbox").click()
# 通过Worker验证
worker_response = driver.execute_async_script("""
const callback = arguments[arguments.length - 1];
const worker = new Worker('/checkbox-worker.js');
worker.postMessage({type: 'get_state'});
worker.onmessage = e => callback(e.data);
""")
assert worker_response["checked"] is True
43. 与WebRTC的集成测试
测试实时协作场景:
python复制def test_webrtc_checkbox_sync():
# 用户A操作
driver.find_element(By.ID, "collab_checkbox").click()
# 验证用户B端同步
remote_state = driver.execute_script("""
return window.rtcDataChannel.receiveUpdate();
""")
assert remote_state["id"] == "collab_checkbox"
assert remote_state["checked"] is True
44. 与WebGL的交互测试
验证3D场景中的控件:
python复制def test_webgl_checkbox():
# 在Canvas中定位虚拟checkbox
action = ActionBuilder(driver)
finger = action.add_pointer_input("mouse", "mouse")
finger.create_pointer_move(
duration=0,
x=300, # WebGL场景中的坐标
y=150,
origin="viewport"
)
finger.create_pointer_down(0)
finger.create_pointer_up(0)
action.perform()
# 验证WebGL状态
gl_state = driver.execute_script("return window.glContext.getUniform()")
assert gl_state["ui_checkbox_enabled"] is True
45. 与WebAudio的集成测试
验证音频反馈:
python复制def test_audio_checkbox():
# 开始音频录制
driver.execute_script("window.audioContext.resume()")
driver.execute_script("window.startRecording()")
# 操作带音效的checkbox
driver.find_element(By.ID, "audio_checkbox").click()
# 分析录音数据
has_click_sound = driver.execute_script("""
const data = window.stopRecording();
return data.some(sample => Math.abs(sample) > 0.5);
""")
assert has_click_sound
46. 与WebUSB的硬件测试
验证物理设备交互:
python复制def test_usb_checkbox():
# 模拟硬件输入
driver.execute_script("""
window.dispatchEvent(new KeyboardEvent('keydown', {
key: ' ',
code: 'Space',
keyCode: 32
}));
""")
# 验证checkbox状态
assert driver.find_element(By.ID, "usb_checkbox").is_selected()
# 验证USB设备状态
usb_state = driver.execute_script("""
return window.usbDevice.controlTransferIn({
requestType: 'vendor',
recipient: 'device',
request: 0x01,
value: 0x02,
index: 0x03
});
""")
assert usb_state.data.getUint8(0) == 1
47. 与WebMIDI的集成测试
验证音乐设备控制:
python复制def test_midi_checkbox():
# 操作MIDI关联的checkbox
driver.find_element(By.ID, "midi_checkbox").click()
# 验证MIDI输出
midi_message = driver.execute_script("""
return window.midiOutput.messages[0];
""")
assert midi_message[0] === 0x90 # Note On事件
assert midi_message[1] === 60 # Middle C
48. 与Web NFC的交互测试
验证近场通信场景:
python复制def test_nfc_checkbox():
# 模拟NFC标签读取
driver.execute_script("""
window.dispatchEvent(new NDEFReadingEvent('reading', {
message: new NDEFMessage({
records: [{
recordType: 'text',
data: 'checked'
}]
})
}));
""")
# 验证自动勾选
assert driver.find_element(By.ID, "nfc_checkbox").is_selected()
49. 与Web Bluetooth的测试
验证蓝牙设备控制:
python复制def test_bluetooth_checkbox():
# 操作蓝牙关联的checkbox
driver.find_element(By.ID, "ble_checkbox").click()
# 验证蓝牙特征值
characteristic = driver.execute_async_script("""
const callback = arguments[arguments.length - 1];
navigator.bluetooth.requestDevice({
filters: [{services: ['heart_rate']}]
})
.then(device => device.gatt.connect())
.then(server => server.getPrimaryService('heart_rate'))
.then(service => service.getCharacteristic('heart_rate_control_point'))
.then(char => char.readValue())
.then(value => callback(new Uint8Array(value.buffer)[0]));
""")
assert characteristic == 1 # 表示开启
50. 与WebXR的虚拟现实测试
验证VR环境中的交互:
python复制def test_vr_checkbox():
# 模拟VR控制器点击
driver.execute_script("""
const event
