如何针对使用 matplotlib 的代码编写单元测试? [英] How can I write unit tests against code that uses matplotlib?

查看:29
本文介绍了如何针对使用 matplotlib 的代码编写单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 python (2.7) 程序,该程序可以生成许多不同的 matplotlib 图(数据不是随机的).我愿意实施一些测试(使用 unittest)以确保生成的数字是正确的.例如,我将预期的图形(数据或图像)存储在某个位置,然后运行我的函数并将结果与​​参考进行比较.有没有办法做到这一点?

I'm working on a python (2.7) program that produce a lot of different matplotlib figure (the data are not random). I'm willing to implement some test (using unittest) to be sure that the generated figures are correct. For instance, I store the expected figure (data or image) in some place, I run my function and compare the result with the reference. Is there a way to do this ?

推荐答案

在我的经验中,图像对比测试最终带来的麻烦超过了他们的价值.如果您想跨多个系统(如 TravisCI)运行持续集成,这些系统可能具有略微不同的字体或可用的绘图后端,则尤其如此.即使功能完全正常工作,也需要做很多工作来保持测试通过.此外,以这种方式进行测试需要将图像保存在您的 git 存储库中,如果您经常更改代码,这会很快导致存储库膨胀.

In my experience, image comparison tests end up bring more trouble than they are worth. This is especially the case if you want to run continuous integration across multiple systems (like TravisCI) that may have slightly different fonts or available drawing backends. It can be a lot of work to keep the tests passing even when the functions work perfectly correctly. Furthermore, testing this way requires keeping images in your git repository, which can quickly lead to repository bloat if you're changing the code often.

在我看来,更好的方法是 (1) 假设 matplotlib 将实际正确绘制图形,并且 (2) 对绘图函数返回的数据运行数值测试.(如果您知道在哪里查看,您也可以随时在 Axes 对象中找到这些数据.)

A better approach in my opinion is to (1) assume matplotlib is going to actually draw the figure correctly, and (2) run numerical tests against the data returned by the plotting functions. (You can also always find this data inside the Axes object if you know where to look.)

例如,假设你想测试一个像这样的简单函数:

For example, say you want to test a simple function like this:

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)

您的单元测试可能看起来像

Your unit test might then look like

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))

这篇关于如何针对使用 matplotlib 的代码编写单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆