【问题标题】:Testing event handling and picking with matplotlib使用 matplotlib 测试事件处理和选择
【发布时间】:2019-04-07 00:37:10
【问题描述】:

根据主题,如何为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 或任何其他测试使用框架。

【问题讨论】:

标签: python unit-testing matplotlib testing


【解决方案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()

【讨论】:

  • 感谢您的精彩回答!模拟事件正是我缺少的部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2018-05-14
  • 2017-03-28
  • 2012-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多