如何等待Graph渲染完毕再断言而不是time.sleep?
解读
在 Dash 自动化测试(pytest + dash.testing)或 Selenium 驱动的端到端测试里,Graph 组件的 SVG/Canvas 真正绘制完成的时间点受三方面影响:
- 后端回调返回数据;
- 浏览器收到 props 后触发 Plotly.js 重绘;
- 重绘动画(750 ms 默认)结束。
如果直接用 time.sleep(2),不仅慢,还极易因网络抖动或 CI 机器性能差异导致“随机失败”。国内面试官想考察的是:你是否熟悉 Dash 暴露的显式等待机制,以及能否在测试代码里用“事件”替代“盲等”,从而写出稳定、可维护的测试用例。
知识点
-
dash.testing 内置等待 API
dash_duo.wait_for_element(selector, timeout=10)dash_duo.wait_for_text_to_equal(selector, text, timeout=10)dash_duo.wait_for_style_to_equal(selector, style_prop, value, timeout=10)
-
Plotly.js 生命周期事件
每次重绘后会触发plotly_afterplot事件;Dash 把这一事件通过dcc.Graph的relayoutData、restyleData、figure等 prop 的变更回传给 Python 端。 -
自定义等待条件
利用WebDriverWait+ 期望条件(EC)封装“SVG 子节点数量 > 0”或“plotly_afterplot 事件已触发”。 -
国内 CI 现状
GitHub Actions / Gitee Go / Jenkins on 阿里云 ECS 常出现“无头浏览器帧率低”问题,显式等待能把单测耗时从 30 s 降到 5 s 以内,是简历亮点。
答案
在 dash.testing 框架里,推荐用“属性变化”或“DOM 结构”作为信号,而不是死等。示例代码:
def test_graph_render(dash_duo):
app = Dash(__name__)
app.layout = html.Div([
dcc.Graph(id='graph', style={'height': 400}),
html.Div(id='signal', children='loading')
])
@app.callback(
Output('graph', 'figure'),
Input('signal', 'children')
)
def update_fig(_):
return px.scatter(x=[1, 2, 3], y=[3, 1, 6])
dash_duo.start_server(app)
# 1. 等待 SVG 元素出现,证明 Plotly 已绘制
dash_duo.wait_for_element('svg.main-svg', timeout=4)
# 2. 断言折线节点数量
lines = dash_duo.find_elements('g.trace.scatter.trace0 path')
assert len(lines) == 1
# 3. 若还需确认动画结束,可再 wait_for_style 检查 opacity 变为 1
dash_duo.wait_for_style_to_equal('g.trace.scatter', 'opacity', '1')
如果不用 dash.testing,而是原生 Selenium,可注入 JS 监听 plotly_afterplot:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
def plotly_afterplot(driver):
return driver.execute_script(
"return window.__plotlyAfterplot === true;"
)
# 在页面加载后注入标记
driver.execute_script(
"""
window.__plotlyAfterplot = false;
document.querySelector('#graph').on('plotly_afterplot', function() {
window.__plotlyAfterplot = true;
});
"""
)
WebDriverWait(driver, 10).until(plotly_afterplot)
以上两种写法均能在“渲染完成”瞬间继续断言,彻底摒弃 time.sleep。
拓展思考
-
多 Graph 并行加载
若仪表盘含 N 个 Graph,可把“每个图都出现 svg.main-svg”封装成wait_for_all_graphs,内部用expected_conditions.all_of。 -
大数据量 Canvas 渲染
当render_mode='webgl'时,SVG 信号不再适用;可改用document.querySelector('canvas').toDataURL() !== initialMD5作为完成标志。 -
与持续集成的结合
国内很多公司用禅道、飞书流水线做质量门禁,把显式等待后的截图通过dash_duo.driver.save_screenshot('graph.png')上传到对象存储,可在 MR 页面直接查看可视化结果,提升评审效率。 -
性能基准
记录“回调返回”到“plotly_afterplot”的间隔,作为回归指标;若某次迭代该间隔增加 20% 以上,自动在代码审查里报警,防止引入冗余数据或过重布局。