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

查看:117
本文介绍了如何针对使用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天全站免登陆