以我的经验,图像比较测试最终带来的麻烦多于其应有的价值。如果要跨多个系统(例如TravisCI)运行持续集成,则可能会出现这种情况,这些系统可能具有略有不同的字体或可用的图形后端。即使功能正常运行,要保持测试通过仍然是很多工作。此外,以这种方式进行测试需要将图像保留在git存储库中,如果您经常更改代码,这会很快导致存储库膨胀。
我认为,更好的方法是(1)假设matplotlib将正确地正确绘制图形,并且(2)对绘图函数返回的数据进行数值测试。(
Axes如果您知道要查找的位置,也可以始终在对象内部找到此数据。)
例如,假设您要测试一个简单的函数,例如:
import numpy as npimport matplotlib.pyplot as pltdef plot_square(x, y): y_squared = np.square(y) return plt.plot(x, y_squared)
您的单元测试可能看起来像
def test_plot_square1(): x, y = [0, 1, 2], [0, 1, 2] line, = plot_square(x, y) x_plot, y_plot = line.get_xydata().T np.testing.assert_array_equal(y_plot, np.square(y))
或者,等效地,
def test_plot_square2(): f, ax = plt.subplots() x, y = [0, 1, 2], [0, 1, 2] plot_square(x, y) x_plot, y_plot = ax.lines[0].get_xydata().T np.testing.assert_array_equal(y_plot, np.square(y))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)