首页 > 解决方案 > 如何为交互式 matplotlib 图形编写单元测试?

问题描述

我想为交互式 matplotlib 图编写单元测试。我的问题是我找不到模拟按键或鼠标按键事件的好方法。我知道 pyautogui,但是我必须关心 matplotlib 窗口在屏幕上的位置(例如,在 TravisCI 上,我怀疑它在不配置的情况下能否正常工作)。我试过研究 Matplotlib 的单元测试,但我找不到任何有用的东西。最好的解决方案是在不涉及 GUI 部分的情况下触发代码内的事件,但到目前为止我无法解决它。

我想出的最简单的例子如下。i您可以使用键在绘图上标记点。我要测试的功能是on_press.

import numpy as np
import matplotlib.pyplot as plt

class PointRecorder:
    def __init__(self, x, y):

        plt.ion()

        self.figure = plt.figure()
        self.cid = self.figure.canvas.mpl_connect("key_press_event", self.on_press)

        self.x = x
        self.y = y
        self.x_points, self.y_points = [2], [0.5]

        plt.plot(self.x, self.y, "r")
        self.pts, = plt.plot(self.x_points, self.y_points, "ko", markersize=6, zorder=99)

        plt.show(block=True)

    def on_press(self, event):
        ix, iy = event.xdata, event.ydata
        if event.inaxes is None:
            return
        if event.key == 'i':
            self.x_points.append(ix)
            self.y_points.append(iy)
            self.pts.set_data(self.x_points, self.y_points)
        if self.pts.stale:
            self.figure.canvas.draw_idle()


    def get_data(self):
        return self.pts.get_data()

if __name__ == "__main__":
    x = np.linspace(0, 6, 100)
    y = np.sin(x)

    graph = PointRecorder(x, y)

    print(*graph.get_data())

你能建议一种如何正确测试这种功能的方法吗?

标签: pythonunit-testingmatplotlib

解决方案


我不是单元测试专家,但我的猜测是您需要实例化一个 Event 对象(在 key_press_event 的情况下,它应该是一个KeyEvent)并graph.on_press(event)从您的测试代码中调用


推荐阅读