1

As per subject, how to write tests for functions that deal with pick event handling in matplotlib?

In particular, given the following minimum working example, how to write a test that would offer 100% coverage?

import numpy as np
import matplotlib.pyplot as plt

def onpick(event):
    ind = event.ind
    print('you clicked on point(s):', ind)

def attach_handler_to_figure(figure):
    figure.canvas.mpl_connect('pick_event', onpick)

def main():
    plt.ion()
    x, y, c, s = np.random.rand(4, 100)
    fig, ax = plt.subplots()
    ax.scatter(x, y, 100*s, c, picker=True)
    attach_handler_to_figure(fig)

main()

The critical part is for me writing tests for the functions onpick and attach_handler_to_figure. Regarding the plotting I find this answer to be satisfying!

MORE INFO: I am not after a way of testing console output. What I am after are test functions, some sort of test_onpick and test_attach_handler_to_figure and test_main (well, in main the challenge is testing the line attach_handler_to_figure(fig)), that can be used by pytest or any other testing framework.

wizclown
  • 313
  • 1
  • 4
  • 16
  • Is [Python: Write unittest for console print](https://stackoverflow.com/questions/33767627/python-write-unittest-for-console-print) what you're looking for? – ImportanceOfBeingErnest Nov 02 '18 at 18:44
  • @ImportanceOfBeingErnest Not really, I'm after a way of simulating the click! But thanks for your input! – wizclown Nov 02 '18 at 19:06

1 Answers1

1

You can of course mock up a pick event. In the following I modified onpick to actually return someting. In order to test console output see Python: Write unittest for console print instead.

import numpy as np
import matplotlib.pyplot as plt

def onpick(event):
    ind = event.ind
    print('you clicked on point(s):', ind)
    return ind

def attach_handler_to_figure(figure):
    figure.canvas.mpl_connect('pick_event', onpick)

def main():
    #plt.ion()
    x, y, c, s = np.random.rand(4, 100)
    fig, ax = plt.subplots()
    ax.scatter(x, y, 100*s, c, picker=True)
    attach_handler_to_figure(fig)


def test_onpick():
    from unittest.mock import Mock

    main()

    event = Mock()
    event.ind = [2]

    ret = onpick(event)
    print(ret)
    assert ret == [2]

test_onpick()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712