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?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With