python - 创建绘图的 Pytest 测试函数

标签 python matplotlib pytest

我有几个创建绘图的函数,我在 Jupyter 笔记本中使用它们来可视化数据。

我想为这些创建基本测试,检查它们是否仍然运行,如果我进行更改,则不会在各种输入上出错。但是,如果我使用 pytest 调用这些函数,创建绘图会导致程序挂起,直到我手动最小化绘图。

import pytest 
import matplotlib.pyplot as plt 

def plot_fn():
    plt.plot([1,2,3])
    plt.show()


def test_plot_fn():
   plot_fn()

如何使用 Pytest 测试“plot_fn”等函数的运行而不出错?我尝试了以下方法,但它不起作用,我认为是因为 plt.show() 导致脚本挂起,因此无法到达 plt.close('all')。

def test_plot_fn():
   plot_fn()
   plt.close('all')

我很高兴更改绘图函数的行为,例如返回 plt 对象?

最佳答案

我不确定matplotlib如何与pytest交互,但似乎您需要使用fixtures才能实现这一点。您还需要在测试中创建某种 assert 语句,该语句将向测试发出信号,以优雅地拆除您的装置。像这样的事情应该达到预期的结果。

import pytest 
import matplotlib.pyplot as plt 

@pytest.fixture(scope='function')
def plot_fn():
    def _plot(points):
        plt.plot(points)
        yield plt.show()
        plt.close('all')
    return _plot


def test_plot_fn(plot_fn):
    points = [1, 2, 3]
    plot_fn(points)
    assert True

如果您想简单地 monkeypatch show 行为,我会像下面所示的那样进行操作。

def test_plot_fn(monkeypatch):
    monkeypatch.setattr(plt, 'show', lambda: None)
    plot_fn()

关于python - 创建绘图的 Pytest 测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60127165/

相关文章:

python - 是否可以 "dynamically"在 Python 中创建局部变量?

python替代正则表达式搜索返回无的元组

python - 如何在 Pandas Python 中更新数据框

python - 使用 Python 填充 Cassandra 数据库

python - 在Python中创建多色散点图

python - 如何通过字符串访问 pytest fixture?

python - 无法在 azure 管道中发布代码覆盖率

python - (如何)我可以将 seaborn despine 函数应用于单个子图?

python - 如何在 scipy.integrate.simps 或 numpy.trapz 之间做出选择?

python - setup_method 中的 py.test session 级固定装置