【问题标题】:Turn off graphs while running unittests运行单元测试时关闭图表
【发布时间】:2017-03-24 09:50:55
【问题描述】:

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

【问题讨论】:

    标签: python unit-testing


    【解决方案1】:

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

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

    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 的调用可以如下修补:

    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

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

    网站上终于有类似的问题了:How to run nosetests without showing of my matplotlib's graph?

    【讨论】:

      【解决方案2】:

      如果在测试中这样做,请勿致电pyplot.show()documentation 还建议对 show 函数使用实验性的 block=False 关键字参数。

      【讨论】:

      • pyplot.show() 在我的一个模块中被调用,而不是在测试中。 block=False 对我不起作用。我认为它已被弃用。
      • 也许从你的测试中调用 pyplot.close("all") 可以解决问题。
      【解决方案3】:

      为了完整起见,我遇到了类似的问题,但为了解决它,我不得不模拟对 matplotlib.pyplot.figure 的调用。我意识到这不是所要求的,但是在遇到这个帖子后我花了一段时间才弄清楚,所以我想在这里发布。

      例如,如果您的 plot_graph.py 看起来像这样:

      import matplotlib.pyplot as plt
      
      def func_plot():
          fig = plt.figure()
          plt.plot([1,2,3,4])
          plt.ylabel('some numbers')
          plt.show()
      

      然后,至少在我的情况下(在没有 X11 转发的终端上运行单元测试,并且在尝试打开绘图时出错),我需要 test_plot_graph.py 中的以下内容来运行我的测试:

      from plot_graph import func_plot
      from unittest.mock import patch
      
      # unittest boilerplate...
      
      @patch('matplotlib.pyplot.figure')
      def test_func_plot(self, mock_fig):
          # whatever tests I want...
          mock_fig.assert_called()  # some assertion on the mock object
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-08
        相关资源
        最近更新 更多