headless 模式下测试鼠标悬停颜色变化?

解读

国内 CI/CD(如阿里云效、腾讯云 CODING、GitHub Actions 国内镜像)普遍采用 无头容器(docker + xvfb)跑单测,而 Matplotlib 的交互功能(hover、pick、widget)又依赖 GUI 事件循环。面试官想知道:

  1. 你是否理解 headless = 无物理屏幕、无窗口管理器;
  2. 能否在 无真实鼠标 的情况下,用 虚拟事件注入 触发 Artist 的 hover 回调;
  3. 能否用 像素采样 或 Artist 属性断言 验证颜色确实变化;
  4. 是否熟悉 Matplotlib 的 后端抽象层(backend_bases.FigureCanvasBase、TimerBase、Event 体系)以及 pytest-mpl、xvfb-run 等国内常用工具链。

知识点

  1. 后端切换:matplotlib.use("Agg") 只能离线绘图,不能收事件;必须改用 headless 交互后端 mpl.use("GTK3Agg") 或 mpl.use("Qt5Agg") 并在容器内起 Xvfb(Xvfb :99 -screen 0 1024x768x24)。
  2. 事件注入:通过 FigureCanvasBase.motion_notify_event(x, y, guiEvent=None) 手动构造 MotionNotify 事件,绕过真实鼠标。
  3. Artist 拾取:给目标 Patch/Line 设 picker=True 或 pickradius,并在 ax.figure.canvas.mpl_connect("motion_notify_event", hover) 里改颜色。
  4. 颜色断言:
    • 属性断言:assert artist.get_facecolor() == 悬停后颜色;
    • 像素断言:fig.canvas.draw() 后 np.array(fig.canvas.buffer_rgba()),再对 鼠标坐标对应像素 做 assert_array_equal(color, expected)。
  5. 异步刷新:headless 下没有 plt.show(),需要 fig.canvas.draw_idle() + TimerBase.single_shot(0, callback) 让 Agg 渲染流水线 走完。
  6. 国内镜像坑:清华 PyPI 源同步延迟,需锁定 pytest-mpl==0.16.1 及以上,否则 baseline 图片哈希 对不上。
  7. CI 模板:.github/workflows/test.yml 里加
    - run: sudo apt-get install -y xvfb libgtk-3-0  
    - run: xvfb-run -a pytest tests/test_hover.py --mpl --cov=matplotlib  
    

答案

# tests/test_hover_headless.py
import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.colors import to_rgba
import pytest

# 强制使用 Agg 作为渲染核,但用 Xvfb 提供虚拟屏幕
matplotlib.use("Agg")          # 仍用 Agg 渲染,但事件系统可用
os.environ["DISPLAY"] = ":99"  # Xvfb 已在 CI 启动

def test_hover_color_change():
    fig, ax = plt.subplots(figsize=(2, 2), dpi=100)
    rect = plt.Rectangle((0.3, 0.3), 0.4, 0.4,
                         facecolor="C0", picker=True)
    ax.add_patch(rect)
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)

    # 用 Agg 画布也能收事件,只要 Xvfb 在跑
    canvas = FigureCanvasAgg(fig)

    hover_color = to_rgba("C3")
    normal_color = rect.get_facecolor()

    def hover(evt):
        if evt.inaxes == ax and rect.contains(evt)[0]:
            rect.set_facecolor(hover_color)
        else:
            rect.set_facecolor(normal_color)
        fig.canvas.draw_idle()

    canvas.mpl_connect("motion_notify_event", hover)

    # 初始颜色
    fig.canvas.draw()
    assert np.allclose(rect.get_facecolor(), normal_color)

    # 注入鼠标进入矩形中心
    x, y = canvas.figure.bbox._transform.transform((0.5, 0.5))
    canvas.motion_notify_event(x, y)
    fig.canvas.draw()  # 确保 Agg 渲染完
    assert np.allclose(rect.get_facecolor(), hover_color)

    # 移出矩形
    canvas.motion_notify_event(0.1, 0.1)
    fig.canvas.draw()
    assert np.allclose(rect.get_facecolor(), normal_color)

运行命令(CI 容器内已装 xvfb)

xvfb-run -a pytest tests/test_hover_headless.py -v

关键点:

  • 用 虚拟事件 代替真实鼠标;
  • 用 属性断言 代替肉眼;
  • 用 xvfb-run 解决 headless 无屏幕问题;
  • 用 fig.canvas.draw() 强制 Agg 走完整渲染流水线,确保颜色写入缓冲区。

拓展思考

  1. GPU 后端:若切换到 WebAgg 或 ipympl,需启动 headless Chrome 并通过 Chrome DevTools 协议 注入鼠标事件,再用 Pillow 截屏 比对像素,适合国内 Streamlit 云托管 场景。
  2. 性能基准:在 400 张 subplot 的仪表板里,hover 回调可能阻塞,需要
    • 用 blitting(canvas.copy_from_bbox + artist.set_animated)减少重绘;
    • 用 TimerBase 做 防抖 16 ms,避免高频事件。
  3. 国产操作系统:统信 UOS 龙芯平台无 X11,只有 Wayland,需编译 Wayland EGL 后端,并改用 weston-headless,事件注入改为 libei 模拟鼠标。
  4. 安全合规:国内金融项目要求 可审计,需把 事件序列(时间、坐标、Artist id、颜色)写进 结构化日志,再上传至 阿里云 SLS,实现 无 UI 回放与 合规审查。