How to run nosetests without showing of my matplot

2019-04-09 01:44发布

问题:

I try to run my test without any messages displaying from my main program. I only want verbose messages from nosetests to display.

For example:

nosetests -v --nologcapture

All of my printout messages from my main program will be gone.

However, the graph that I call in my main program (plt.show() from matplotlib) still shows up.

How do I run the tests without matplotlib's graph showing up?

回答1:

I assume that you're calling unittests on your code, so my recommendation would be for you to install the python Mock library. Any tests that will exercise the plt.show() function should mock it out to basically do nothing.

Here's an rough example of the idea inside your unittests:

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 ...

The patch function will override the normal show function with this new mock_show which you could name to anything. This should basically make the show now do nothing in your tests and not have the graph show up.