python - 如何为交互式 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())
你能建议一种如何正确测试这种功能的方法吗?
解决方案
我不是单元测试专家,但我的猜测是您需要实例化一个 Event 对象(在 key_press_event 的情况下,它应该是一个KeyEvent)并graph.on_press(event)
从您的测试代码中调用
推荐阅读
- c++ - 我需要在构造函数成员初始化器列表中间调用一个 void 函数,以便可以正确初始化其他对象
- python - 教科书示例中的索引超出范围
- php - DepDrop Yii。Child DrList 未正确显示
- azure - Graph API 可以替代 Azure 门户吗?
- node.js - 以编程方式安装或更新到最新版本的全局包的最快方法是什么?
- javascript - 尝试更新 chart.js 图表中的数据
- java - 动态想在cardview中上传图片
- python - 从用户名 Discord.py 获取用户 ID
- javascript - 如何在 Stripe Checkout 中添加运费总额?
- rust - 在实现的函数 Rust 中为 self struct 赋值