In my 经验 http://stanford.edu/~mwaskom/software/seaborn/,图像比较测试最终会带来比其价值更多的麻烦。如果您想要跨多个系统(例如 TravisCI)运行持续集成,而这些系统的字体或可用绘图后端可能略有不同,则尤其如此。即使功能完美正确地工作,保持测试通过也可能需要做很多工作。此外,这种测试方式需要将图像保留在 git 存储库中,如果您经常更改代码,这可能会很快导致存储库膨胀。
我认为更好的方法是 (1) 假设 matplotlib 实际上会正确绘制图形,并且 (2) 对绘图函数返回的数据运行数值测试。 (您也可以随时在Axes
如果您知道去哪里查看,则反对。)
例如,假设您想测试一个像这样的简单函数:
import numpy as np
import matplotlib.pyplot as plt
def 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))