我正在开发一个 Python 库,最近想将
pytest
集成到我的开发工作流程中。我尝试运行一个简单的测试并通过了,但我收到了警告:
.venv\Lib\site-packages\pygame\pkgdata.py:25
D:\dev\python\physiscript\.venv\Lib\site-packages\pygame\pkgdata.py:25: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html
from pkg_resources import resource_stream, resource_exists
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
从警告消息来看,这个警告似乎来自我在项目中使用的
pygame
(实际上是pygame-ce
)。但是,当我运行我的应用程序时,我没有看到此警告,并且之前在使用 pygame
时从未收到过此警告。这是示例测试:
# Implicitly imports pygame for other library functionality, and thus trigger the warning
import mylib
# sample test
def test_demo():
assert True
图书馆的
__init__.py
:
import pygame
def print_version():
print(pygame.version.ver)
我正常使用库时,没有任何警告,也没有问题:
import mylib
mylib.print_version()
有人可以解释一下为什么我收到此警告时使用
pytest
,但在我正常运行应用程序时却没有收到此警告?
你是对的,pygame 使用了 pkg_resources 中已弃用的 API,这就是为什么首先出现警告的原因。在 Python 中,警告默认关闭,并在运行单元测试时启用。
您可以通过运行以下命令轻松禁用运行时的所有警告
pytest
:
pytest -p no:warnings
或者通过设置环境变量:
export PYTHONWARNINGS="ignore"
pytest
或按类别:
pytest -W ignore::DeprecationWarning
或者以编程方式,但我认为这更复杂,并且使用前面的选项更适合 CI 管道。
有关更多信息,请查看文档: https://docs.python.org/3/library/warnings.html