使用matplotlib测试事件处理和选择

时间:2018-11-02 18:36:50

标签: python unit-testing matplotlib testing

按照主题,如何为matplotlib中处理pick event handling的函数编写测试?

特别是,给出以下最小工作示例,如何编写可提供100%覆盖率的测试?

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

对我来说,关键部分是为功能onpickattach_handler_to_figure编写测试。关于情节,我发现this answer很令人满意!

更多信息:我不是想测试控制台输出。我需要的是测试功能,可以使用某种类型的test_onpicktest_attach_handler_to_figuretest_main(嗯,主要的挑战是测试行attach_handler_to_figure(fig))由pytest或任何其他测试框架提供。

1 个答案:

答案 0 :(得分:1)

您当然可以模拟选择事件。在下文中,我修改了onpick以实际返回某物。为了测试控制台输出,请参阅Python: Write unittest for console print

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