1

I am doing a unit test (using pytest) of a plot function that calls a plot method via mplfiance (essentially a candlestick plot using matplotlib).

I would like to path the call of the plot function in my test so that it wont actually create the graph. I would just like to see if the parameters are correct when i call the function.

For example

def plot_something(param1, param2):
    # doing something with param1 and para2
    param1 += 1
    param2 *= 2
    # below is the actual plotting where I would like to patch
    make_plot(param1, param2)

def make_plot(param1, param2):
    # make plot here
    plot(param1, param2)

How can I create a test case to just make sure 1) both plot_something() and make_plot() are called. 2) the parameters are asserted 3) no actual graph is actually display on the screen?

I suppose patching is the way to go to replace make_plot() call with something in the test function. But I don't know how exactly.

Many thanks for your advice.

1

1 Answer 1

2

This made me curious to test the mock module myself. Here is my code that seems to work fine:

from unittest import TestCase, main
from unittest.mock import Mock
import pylab

def plot_something():
    x = [1,2,3]
    y = [3,1,2]
    pylab.plot(x, y, "o-")
    pylab.show()


class TestPlot(TestCase):
    def test_plot_something(self):
        # save the original methods for later use (if required)
        pyplot, pyshow = pylab.plot, pylab.show

        pylab.plot, pylab.show = Mock(), Mock()
        plot_something()

        pylab.plot.assert_called_once_with([1,2,3], [3,1,2], "o-")
        pylab.show.assert_called_once_with()

        # restore the original ones again
        pylab.plot, pylab.show = pyplot, pyshow

    def test_plot_again_but_plot_really(self):
        # this actually plots
        plot_something()


if __name__ == "__main__":
    main()

So, here I even patched the pylab methods. It's of course even easier to intervene on the higher level (whether plot_someting is called).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. While I couldn't directly incorporate that, I took the idea and use @patch decorator for my testcase function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.