运行单元测试时关闭图形 [英] Turn off graphs while running unittests

查看:31
本文介绍了运行单元测试时关闭图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 unittest 库测试我的模块.这包括使用 matplotlib 库绘制一些图形.目前的问题是每次绘制图形时测试都会暂停,并且只有在我关闭图形后才会恢复.我怎样才能避免这种情况?

I am testing out my module using the unittest library. This includes plotting some graphs using the matplotlib library. The issue at the moment is that the testing pauses every time a graph is plotted, and it only resumes after I close the graph. How can I avoid this?

推荐答案

我将根据 matplotlib 教程中的简单示例代码为我的答案建模:http://matplotlib.org/users/pyplot_tutorial.html

I will model my answer after the simple example code from the matplotlib tutorial: http://matplotlib.org/users/pyplot_tutorial.html

假设我们有以下模块,plot_graph.py 需要测试:

Let's assume we have the following module, plot_graph.py to be tested:

import matplotlib.pyplot as plt

def func_plot():
    plt.plot([1,2,3,4])
    plt.ylabel('some numbers')
    plt.show()

if __name__ == "__main__":
    func_plot()

show 的调用可以打补丁如下:

The calls to show can be patched as follows:

from plot_graph import func_plot
from unittest.mock import patch

@patch("plot_graph.plt.show")
def test_plot(mock_show):
    assert func_plot() == None

如您所见,您应该修补对 pyplot.show() 的调用.您可以在文档中找到有关修补和模拟的更多信息:https://docs.python.org/3/library/unittest.mock.html.

As you can see, you should patch the calls to pyplot.show(). You can find more about patching and mocking in the docs: https://docs.python.org/3/library/unittest.mock.html.

通常关于在哪里打补丁的部分非常有用:https://docs.python.org/3/library/unittest.mock.html#where-to-patch

Usually the section about where to patch is really useful: https://docs.python.org/3/library/unittest.mock.html#where-to-patch

网站上终于有类似的问题了:如何在不显示我的 matplotlib 图形的情况下运行鼻子测试?

Finally there are similar question already on the site: How to run nosetests without showing of my matplotlib's graph?

这篇关于运行单元测试时关闭图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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