Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn off graphs while running unittests

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?

like image 307
bluprince13 Avatar asked Mar 24 '17 09:03

bluprince13


1 Answers

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

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

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

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.

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

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

like image 133
Enrique Saez Avatar answered Oct 04 '22 04:10

Enrique Saez