首页 > 解决方案 > matplotlib 测试无头且没有警告

问题描述

我通常用pytest测试我的 Python 包

pytest

如果测试包含matplotlib绘图例程,则会弹出我必须手动关闭的窗口。为了防止这种情况,我通常通过调用 pytest 来无头运行测试

MPLBACKEND=Agg pytest

或通过设置

import matplotlib
matplotlib.use("Agg")

在测试文件中。两种变体都会产生警告

UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
    plt.show()

我宁愿避免。大量的 agg-warnings 可能会隐藏我关心的实际警告。

也许还有另一种无头运行 matplotlib 测试的规范方式。有什么提示吗?

标签: pythonmatplotlib

解决方案


在 pytest 中,有多种方法可以忽略警告,请参见此处。一种可能性是通过装饰函数来忽略单个测试的警告

@pytest.mark.filterwarnings(
    'ignore:Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.:UserWarning'
)

如果您想忽略项目中的所有此类警告,请添加

[tool.pytest.ini_options]
filterwarnings = [
  'ignore:Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.:UserWarning'
]

到你的pyproject.toml

[pytest]
filterwarnings =
    ignore:Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.:UserWarning

到你的pytest.ini.


推荐阅读