如何运行nosetests而不显示我的matplotlib图表?

fro*_*hem 6 python tdd unit-testing nose

我尝试运行我的测试,没有任何消息从我的主程序显示.我只想显示来自nosetests的详细消息.

例如:

nosetests -v --nologcapture

我的主程序中的所有打印输出消息都将消失.

但是,我在主程序中调用的图形(plt.show()来自matplotlib)仍然显示出来.

如何在没有出现matplotlib图表的情况下运行测试?

Jay*_*son 7

我假设你在你的代码上调用unittests,所以我建议你安装python Mock库.任何将执行该plt.show()功能的测试都应该嘲笑它基本上什么都不做.

以下是您的单元测试中的想法的一个粗略示例:

from mock import patch


... unittest boiler plate stuff ...

@patch("matplotlib.pyplot.show")
def testMyCode(self, mock_show):
    mock_show.return_value = None  #probably not necessary here in your case
    ... rest of test code ...
Run Code Online (Sandbox Code Playgroud)

patch函数将覆盖正常的show函数,这个new mock_show可以命名为任何东西.这应该基本上使节目现在在你的测试中什么都不做,而不是让图表显示出来.